1 """Add things to old Pythons so I can pretend they are newer.""" |
1 """Add things to old Pythons so I can pretend they are newer.""" |
2 |
2 |
3 # pylint: disable-msg=W0622 |
3 # This file does lots of tricky stuff, so disable a bunch of lintisms. |
4 # (Redefining built-in blah) |
4 # pylint: disable-msg=F0401,W0611,W0622 |
5 # The whole point of this file is to redefine built-ins, so shut up about it. |
5 # F0401: Unable to import blah |
|
6 # W0611: Unused import blah |
|
7 # W0622: Redefining built-in blah |
6 |
8 |
|
9 import os, sys |
7 |
10 |
8 # Python 2.3 doesn't have `set` |
11 # Python 2.3 doesn't have `set` |
9 try: |
12 try: |
10 set = set # new in 2.4 |
13 set = set # new in 2.4 |
11 except NameError: |
14 except NameError: |
12 # (Redefining built-in 'set') |
|
13 from sets import Set as set |
15 from sets import Set as set |
14 |
16 |
15 |
17 |
16 # Python 2.3 doesn't have `sorted`. |
18 # Python 2.3 doesn't have `sorted`. |
17 try: |
19 try: |
20 def sorted(iterable): |
22 def sorted(iterable): |
21 """A 2.3-compatible implementation of `sorted`.""" |
23 """A 2.3-compatible implementation of `sorted`.""" |
22 lst = list(iterable) |
24 lst = list(iterable) |
23 lst.sort() |
25 lst.sort() |
24 return lst |
26 return lst |
|
27 |
|
28 # Pythons 2 and 3 differ on where to get StringIO |
|
29 |
|
30 try: |
|
31 from cStringIO import StringIO |
|
32 BytesIO = StringIO |
|
33 except ImportError: |
|
34 from io import StringIO, BytesIO |
|
35 |
|
36 # What's a string called? |
|
37 |
|
38 try: |
|
39 string_class = basestring |
|
40 except NameError: |
|
41 string_class = str |
|
42 |
|
43 # Where do pickles come from? |
|
44 |
|
45 try: |
|
46 import cPickle as pickle |
|
47 except ImportError: |
|
48 import pickle |
|
49 |
|
50 # range or xrange? |
|
51 |
|
52 try: |
|
53 range = xrange |
|
54 except NameError: |
|
55 range = range |
|
56 |
|
57 # Exec is a statement in Py2, a function in Py3 |
|
58 |
|
59 if sys.hexversion > 0x03000000: |
|
60 def exec_function(source, filename, global_map): |
|
61 """A wrapper around exec().""" |
|
62 exec(compile(source, filename, "exec"), global_map) |
|
63 else: |
|
64 # OK, this is pretty gross. In Py2, exec was a statement, but that will |
|
65 # be a syntax error if we try to put it in a Py3 file, even if it is never |
|
66 # executed. So hide it inside an evaluated string literal instead. |
|
67 eval(compile("""\ |
|
68 def exec_function(source, filename, global_map): |
|
69 exec compile(source, filename, "exec") in global_map |
|
70 """, |
|
71 "<exec_function>", "exec" |
|
72 )) |