|
20 | 20 | followed by clean Python 3 code (with a few restrictions) that can run
|
21 | 21 | unchanged on Python 2.7.
|
22 | 22 |
|
23 |
| -After the imports, this code runs identically on Python 3 and 2:: |
24 |
| - |
25 |
| - # Support for renamed standard library modules via import hooks |
26 |
| - from http.client import HttpConnection |
27 |
| - from itertools import filterfalse |
28 |
| - from test import support |
29 |
| -
|
30 |
| - # Backported Py3 bytes object |
31 |
| - b = bytes(b'ABCD') |
32 |
| - assert list(b) == [65, 66, 67, 68] |
33 |
| - assert repr(b) == "b'ABCD'" |
34 |
| - # These raise TypeErrors: |
35 |
| - # b + u'EFGH' |
36 |
| - # bytes(b',').join([u'Fred', u'Bill']) |
37 |
| -
|
38 |
| - # Backported Py3 str object |
39 |
| - s = str(u'ABCD') |
40 |
| - assert s != b'ABCD' |
41 |
| - assert isinstance(s.encode('utf-8'), bytes) |
42 |
| - assert isinstance(b.decode('utf-8'), str) |
43 |
| - assert repr(s) == 'ABCD' # consistent repr with Py3 (no u prefix) |
44 |
| - # These raise TypeErrors: |
45 |
| - # b'B' in s |
46 |
| - # s.find(b'A') |
47 |
| -
|
48 |
| - # Extra arguments for the open() function |
49 |
| - f = open('japanese.txt', encoding='utf-8', errors='replace') |
50 |
| - |
51 |
| - # New iterable range object with slicing support |
52 |
| - for i in range(10**15)[:10]: |
53 |
| - pass |
54 |
| - |
55 |
| - # Other iterators: map, zip, filter |
56 |
| - my_iter = zip(range(3), ['a', 'b', 'c']) |
57 |
| - assert my_iter != list(my_iter) |
58 |
| - |
59 |
| - # New simpler super() function: |
60 |
| - class VerboseList(list): |
61 |
| - def append(self, item): |
62 |
| - print('Adding an item') |
63 |
| - super().append(item) |
64 |
| - |
65 |
| - # These raise NameErrors: |
66 |
| - # apply(), cmp(), coerce(), reduce(), xrange(), etc. |
67 |
| - |
68 |
| - # The round() function behaves as it does in Python 3, using |
69 |
| - # "Banker's Rounding" to the nearest even last digit: |
70 |
| - assert round(0.1250, 2) == 0.12 |
71 |
| - |
72 |
| - # input() replaces Py2's raw_input() (with no eval()): |
73 |
| - name = input('What is your name? ') |
74 |
| - print('Hello ' + name) |
75 |
| -
|
76 |
| -
|
77 | 23 | On Python 3, the import lines have zero effect (and zero namespace
|
78 | 24 | pollution).
|
79 | 25 |
|
|
0 commit comments