root / elixir / tags / 0.6.0 / elixir / py23compat.py

Revision 347, 2.4 kB (checked in by ged, 6 years ago)

removed trailing spaces

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1# Some helper functions to get by without Python 2.4
2
3# set
4try:
5    set = set
6except NameError:
7    from sets import Set as set
8
9orig_cmp = cmp
10# [].sort
11def sort_list(l, cmp=None, key=None, reverse=False):
12    try:
13        l.sort(cmp, key, reverse)
14    except TypeError, e:
15        if not str(e).startswith('sort expected at most 1 arguments'):
16            raise
17        if cmp is None:
18            cmp = orig_cmp
19        if key is not None:
20            # the cmp=cmp parameter is required to get the original comparator
21            # into the lambda namespace
22            cmp = lambda self, other, cmp=cmp: cmp(key(self), key(other))
23        if reverse:
24            cmp = lambda self, other, cmp=cmp: -cmp(self,other)
25        l.sort(cmp)
26
27# sorted
28try:
29    sorted = sorted
30except NameError:
31    # global name 'sorted' doesn't exist in Python2.3
32    # this provides a poor-man's emulation of the sorted built-in method
33    def sorted(l, cmp=None, key=None, reverse=False):
34        sorted_list = list(l)
35        sort_list(sorted_list, cmp, key, reverse)
36        return sorted_list
37
38# rsplit
39try:
40    ''.rsplit
41    def rsplit(s, delim, maxsplit):
42        return s.rsplit(delim, maxsplit)
43
44except AttributeError:
45    def rsplit(s, delim, maxsplit):
46        """Return a list of the words of the string s, scanning s
47        from the end. To all intents and purposes, the resulting
48        list of words is the same as returned by split(), except
49        when the optional third argument maxsplit is explicitly
50        specified and nonzero. When maxsplit is nonzero, at most
51        maxsplit number of splits - the rightmost ones - occur,
52        and the remainder of the string is returned as the first
53        element of the list (thus, the list will have at most
54        maxsplit+1 elements). New in version 2.4.
55        >>> rsplit('foo.bar.baz', '.', 0)
56        ['foo.bar.baz']
57        >>> rsplit('foo.bar.baz', '.', 1)
58        ['foo.bar', 'baz']
59        >>> rsplit('foo.bar.baz', '.', 2)
60        ['foo', 'bar', 'baz']
61        >>> rsplit('foo.bar.baz', '.', 99)
62        ['foo', 'bar', 'baz']
63        """
64        assert maxsplit >= 0
65
66        if maxsplit == 0: return [s]
67
68        # the following lines perform the function, but inefficiently.
69        #  This may be adequate for compatibility purposes
70        items = s.split(delim)
71        if maxsplit < len(items):
72            items[:-maxsplit] = [delim.join(items[:-maxsplit])]
73        return items
Note: See TracBrowser for help on using the browser.