File: compatible_idioms.rst

package info (click to toggle)
python-future 0.18.2-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,264 kB
  • sloc: python: 43,246; makefile: 136; sh: 29
file content (1457 lines) | stat: -rw-r--r-- 32,354 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
.. _compatible-idioms:

Cheat Sheet: Writing Python 2-3 compatible code
===============================================

-  **Copyright (c):** 2013-2019 Python Charmers Pty Ltd, Australia.
-  **Author:** Ed Schofield.
-  **Licence:** Creative Commons Attribution.

A PDF version is here: http://python-future.org/compatible\_idioms.pdf

This notebook shows you idioms for writing future-proof code that is
compatible with both versions of Python: 2 and 3. It accompanies Ed
Schofield's talk at PyCon AU 2014, "Writing 2/3 compatible code". (The
video is here: http://www.youtube.com/watch?v=KOqk8j11aAI&t=10m14s.)

Minimum versions:

-  Python 2: 2.7+
-  Python 3: 3.4+

Setup
-----

The imports below refer to these ``pip``-installable packages on PyPI:

::

    import future        # pip install future
    import builtins      # pip install future
    import past          # pip install future
    import six           # pip install six

The following scripts are also ``pip``-installable:

::

    futurize             # pip install future
    pasteurize           # pip install future

See http://python-future.org and https://pythonhosted.org/six/ for more
information.

Essential syntax differences
----------------------------

print
~~~~~

.. code:: python

    # Python 2 only:
    print 'Hello'
.. code:: python

    # Python 2 and 3:
    print('Hello')
To print multiple strings, import ``print_function`` to prevent Py2 from
interpreting it as a tuple:

.. code:: python

    # Python 2 only:
    print 'Hello', 'Guido'
.. code:: python

    # Python 2 and 3:
    from __future__ import print_function    # (at top of module)

    print('Hello', 'Guido')
.. code:: python

    # Python 2 only:
    print >> sys.stderr, 'Hello'
.. code:: python

    # Python 2 and 3:
    from __future__ import print_function

    print('Hello', file=sys.stderr)
.. code:: python

    # Python 2 only:
    print 'Hello',
.. code:: python

    # Python 2 and 3:
    from __future__ import print_function

    print('Hello', end='')
Raising exceptions
~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    raise ValueError, "dodgy value"
.. code:: python

    # Python 2 and 3:
    raise ValueError("dodgy value")
Raising exceptions with a traceback:

.. code:: python

    # Python 2 only:
    traceback = sys.exc_info()[2]
    raise ValueError, "dodgy value", traceback
.. code:: python

    # Python 3 only:
    raise ValueError("dodgy value").with_traceback()
.. code:: python

    # Python 2 and 3: option 1
    from six import reraise as raise_
    # or
    from future.utils import raise_

    traceback = sys.exc_info()[2]
    raise_(ValueError, "dodgy value", traceback)
.. code:: python

    # Python 2 and 3: option 2
    from future.utils import raise_with_traceback

    raise_with_traceback(ValueError("dodgy value"))
Exception chaining (PEP 3134):

.. code:: python

    # Setup:
    class DatabaseError(Exception):
        pass
.. code:: python

    # Python 3 only
    class FileDatabase:
        def __init__(self, filename):
            try:
                self.file = open(filename)
            except IOError as exc:
                raise DatabaseError('failed to open') from exc
.. code:: python

    # Python 2 and 3:
    from future.utils import raise_from

    class FileDatabase:
        def __init__(self, filename):
            try:
                self.file = open(filename)
            except IOError as exc:
                raise_from(DatabaseError('failed to open'), exc)
.. code:: python

    # Testing the above:
    try:
        fd = FileDatabase('non_existent_file.txt')
    except Exception as e:
        assert isinstance(e.__cause__, IOError)    # FileNotFoundError on Py3.3+ inherits from IOError
Catching exceptions
~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    try:
        ...
    except ValueError, e:
        ...
.. code:: python

    # Python 2 and 3:
    try:
        ...
    except ValueError as e:
        ...
Division
~~~~~~~~

Integer division (rounding down):

.. code:: python

    # Python 2 only:
    assert 2 / 3 == 0
.. code:: python

    # Python 2 and 3:
    assert 2 // 3 == 0
"True division" (float division):

.. code:: python

    # Python 3 only:
    assert 3 / 2 == 1.5
.. code:: python

    # Python 2 and 3:
    from __future__ import division    # (at top of module)

    assert 3 / 2 == 1.5
"Old division" (i.e. compatible with Py2 behaviour):

.. code:: python

    # Python 2 only:
    a = b / c            # with any types
.. code:: python

    # Python 2 and 3:
    from past.utils import old_div

    a = old_div(b, c)    # always same as / on Py2
Long integers
~~~~~~~~~~~~~

Short integers are gone in Python 3 and ``long`` has become ``int``
(without the trailing ``L`` in the ``repr``).

.. code:: python

    # Python 2 only
    k = 9223372036854775808L

    # Python 2 and 3:
    k = 9223372036854775808
.. code:: python

    # Python 2 only
    bigint = 1L

    # Python 2 and 3
    from builtins import int
    bigint = int(1)
To test whether a value is an integer (of any kind):

.. code:: python

    # Python 2 only:
    if isinstance(x, (int, long)):
        ...

    # Python 3 only:
    if isinstance(x, int):
        ...

    # Python 2 and 3: option 1
    from builtins import int    # subclass of long on Py2

    if isinstance(x, int):             # matches both int and long on Py2
        ...

    # Python 2 and 3: option 2
    from past.builtins import long

    if isinstance(x, (int, long)):
        ...
Octal constants
~~~~~~~~~~~~~~~

.. code:: python

    0644     # Python 2 only
.. code:: python

    0o644    # Python 2 and 3
Backtick repr
~~~~~~~~~~~~~

.. code:: python

    `x`      # Python 2 only
.. code:: python

    repr(x)  # Python 2 and 3
Metaclasses
~~~~~~~~~~~

.. code:: python

    class BaseForm(object):
        pass

    class FormType(type):
        pass
.. code:: python

    # Python 2 only:
    class Form(BaseForm):
        __metaclass__ = FormType
        pass
.. code:: python

    # Python 3 only:
    class Form(BaseForm, metaclass=FormType):
        pass
.. code:: python

    # Python 2 and 3:
    from six import with_metaclass
    # or
    from future.utils import with_metaclass

    class Form(with_metaclass(FormType, BaseForm)):
        pass
Strings and bytes
-----------------

Unicode (text) string literals
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you are upgrading an existing Python 2 codebase, it may be preferable
to mark up all string literals as unicode explicitly with ``u``
prefixes:

.. code:: python

    # Python 2 only
    s1 = 'The Zen of Python'
    s2 = u'きたないのよりきれいな方がいい\n'

    # Python 2 and 3
    s1 = u'The Zen of Python'
    s2 = u'きたないのよりきれいな方がいい\n'
The ``futurize`` and ``python-modernize`` tools do not currently offer
an option to do this automatically.

If you are writing code for a new project or new codebase, you can use
this idiom to make all string literals in a module unicode strings:

.. code:: python

    # Python 2 and 3
    from __future__ import unicode_literals    # at top of module

    s1 = 'The Zen of Python'
    s2 = 'きたないのよりきれいな方がいい\n'
See http://python-future.org/unicode\_literals.html for more discussion
on which style to use.

Byte-string literals
~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only
    s = 'This must be a byte-string'

    # Python 2 and 3
    s = b'This must be a byte-string'
To loop over a byte-string with possible high-bit characters, obtaining
each character as a byte-string of length 1:

.. code:: python

    # Python 2 only:
    for bytechar in 'byte-string with high-bit chars like \xf9':
        ...

    # Python 3 only:
    for myint in b'byte-string with high-bit chars like \xf9':
        bytechar = bytes([myint])

    # Python 2 and 3:
    from builtins import bytes
    for myint in bytes(b'byte-string with high-bit chars like \xf9'):
        bytechar = bytes([myint])
As an alternative, ``chr()`` and ``.encode('latin-1')`` can be used to
convert an int into a 1-char byte string:

.. code:: python

    # Python 3 only:
    for myint in b'byte-string with high-bit chars like \xf9':
        char = chr(myint)    # returns a unicode string
        bytechar = char.encode('latin-1')

    # Python 2 and 3:
    from builtins import bytes, chr
    for myint in bytes(b'byte-string with high-bit chars like \xf9'):
        char = chr(myint)    # returns a unicode string
        bytechar = char.encode('latin-1')    # forces returning a byte str
basestring
~~~~~~~~~~

.. code:: python

    # Python 2 only:
    a = u'abc'
    b = 'def'
    assert (isinstance(a, basestring) and isinstance(b, basestring))

    # Python 2 and 3: alternative 1
    from past.builtins import basestring    # pip install future

    a = u'abc'
    b = b'def'
    assert (isinstance(a, basestring) and isinstance(b, basestring))
.. code:: python

    # Python 2 and 3: alternative 2: refactor the code to avoid considering
    # byte-strings as strings.

    from builtins import str
    a = u'abc'
    b = b'def'
    c = b.decode()
    assert isinstance(a, str) and isinstance(c, str)
    # ...
unicode
~~~~~~~

.. code:: python

    # Python 2 only:
    templates = [u"blog/blog_post_detail_%s.html" % unicode(slug)]
.. code:: python

    # Python 2 and 3: alternative 1
    from builtins import str
    templates = [u"blog/blog_post_detail_%s.html" % str(slug)]
.. code:: python

    # Python 2 and 3: alternative 2
    from builtins import str as text
    templates = [u"blog/blog_post_detail_%s.html" % text(slug)]
StringIO
~~~~~~~~

.. code:: python

    # Python 2 only:
    from StringIO import StringIO
    # or:
    from cStringIO import StringIO

    # Python 2 and 3:
    from io import BytesIO     # for handling byte strings
    from io import StringIO    # for handling unicode strings
Imports relative to a package
-----------------------------

Suppose the package is:

::

    mypackage/
        __init__.py
        submodule1.py
        submodule2.py


and the code below is in ``submodule1.py``:

.. code:: python

    # Python 2 only:
    import submodule2
.. code:: python

    # Python 2 and 3:
    from . import submodule2
.. code:: python

    # Python 2 and 3:
    # To make Py2 code safer (more like Py3) by preventing
    # implicit relative imports, you can also add this to the top:
    from __future__ import absolute_import
Dictionaries
------------

.. code:: python

    heights = {'Fred': 175, 'Anne': 166, 'Joe': 192}
Iterating through ``dict`` keys/values/items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Iterable dict keys:

.. code:: python

    # Python 2 only:
    for key in heights.iterkeys():
        ...
.. code:: python

    # Python 2 and 3:
    for key in heights:
        ...
Iterable dict values:

.. code:: python

    # Python 2 only:
    for value in heights.itervalues():
        ...
.. code:: python

    # Idiomatic Python 3
    for value in heights.values():    # extra memory overhead on Py2
        ...
.. code:: python

    # Python 2 and 3: option 1
    from builtins import dict

    heights = dict(Fred=175, Anne=166, Joe=192)
    for key in heights.values():    # efficient on Py2 and Py3
        ...
.. code:: python

    # Python 2 and 3: option 2
    from future.utils import itervalues
    # or
    from six import itervalues

    for key in itervalues(heights):
        ...
Iterable dict items:

.. code:: python

    # Python 2 only:
    for (key, value) in heights.iteritems():
        ...
.. code:: python

    # Python 2 and 3: option 1
    for (key, value) in heights.items():    # inefficient on Py2
        ...
.. code:: python

    # Python 2 and 3: option 2
    from future.utils import viewitems

    for (key, value) in viewitems(heights):   # also behaves like a set
        ...
.. code:: python

    # Python 2 and 3: option 3
    from future.utils import iteritems
    # or
    from six import iteritems

    for (key, value) in iteritems(heights):
        ...
dict keys/values/items as a list
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

dict keys as a list:

.. code:: python

    # Python 2 only:
    keylist = heights.keys()
    assert isinstance(keylist, list)
.. code:: python

    # Python 2 and 3:
    keylist = list(heights)
    assert isinstance(keylist, list)
dict values as a list:

.. code:: python

    # Python 2 only:
    heights = {'Fred': 175, 'Anne': 166, 'Joe': 192}
    valuelist = heights.values()
    assert isinstance(valuelist, list)
.. code:: python

    # Python 2 and 3: option 1
    valuelist = list(heights.values())    # inefficient on Py2
.. code:: python

    # Python 2 and 3: option 2
    from builtins import dict

    heights = dict(Fred=175, Anne=166, Joe=192)
    valuelist = list(heights.values())
.. code:: python

    # Python 2 and 3: option 3
    from future.utils import listvalues

    valuelist = listvalues(heights)
.. code:: python

    # Python 2 and 3: option 4
    from future.utils import itervalues
    # or
    from six import itervalues

    valuelist = list(itervalues(heights))
dict items as a list:

.. code:: python

    # Python 2 and 3: option 1
    itemlist = list(heights.items())    # inefficient on Py2
.. code:: python

    # Python 2 and 3: option 2
    from future.utils import listitems

    itemlist = listitems(heights)
.. code:: python

    # Python 2 and 3: option 3
    from future.utils import iteritems
    # or
    from six import iteritems

    itemlist = list(iteritems(heights))
Custom class behaviour
----------------------

Custom iterators
~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only
    class Upper(object):
        def __init__(self, iterable):
            self._iter = iter(iterable)
        def next(self):          # Py2-style
            return self._iter.next().upper()
        def __iter__(self):
            return self

    itr = Upper('hello')
    assert itr.next() == 'H'     # Py2-style
    assert list(itr) == list('ELLO')
.. code:: python

    # Python 2 and 3: option 1
    from builtins import object

    class Upper(object):
        def __init__(self, iterable):
            self._iter = iter(iterable)
        def __next__(self):      # Py3-style iterator interface
            return next(self._iter).upper()  # builtin next() function calls
        def __iter__(self):
            return self

    itr = Upper('hello')
    assert next(itr) == 'H'      # compatible style
    assert list(itr) == list('ELLO')
.. code:: python

    # Python 2 and 3: option 2
    from future.utils import implements_iterator

    @implements_iterator
    class Upper(object):
        def __init__(self, iterable):
            self._iter = iter(iterable)
        def __next__(self):                  # Py3-style iterator interface
            return next(self._iter).upper()  # builtin next() function calls
        def __iter__(self):
            return self

    itr = Upper('hello')
    assert next(itr) == 'H'
    assert list(itr) == list('ELLO')
Custom ``__str__`` methods
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    class MyClass(object):
        def __unicode__(self):
            return 'Unicode string: \u5b54\u5b50'
        def __str__(self):
            return unicode(self).encode('utf-8')

    a = MyClass()
    print(a)    # prints encoded string
.. code:: python

    # Python 2 and 3:
    from future.utils import python_2_unicode_compatible

    @python_2_unicode_compatible
    class MyClass(object):
        def __str__(self):
            return u'Unicode string: \u5b54\u5b50'

    a = MyClass()
    print(a)    # prints string encoded as utf-8 on Py2

.. parsed-literal::

    Unicode string: 孔子


Custom ``__nonzero__`` vs ``__bool__`` method:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    class AllOrNothing(object):
        def __init__(self, l):
            self.l = l
        def __nonzero__(self):
            return all(self.l)

    container = AllOrNothing([0, 100, 200])
    assert not bool(container)
.. code:: python

    # Python 2 and 3:
    from builtins import object

    class AllOrNothing(object):
        def __init__(self, l):
            self.l = l
        def __bool__(self):
            return all(self.l)

    container = AllOrNothing([0, 100, 200])
    assert not bool(container)
Lists versus iterators
----------------------

xrange
~~~~~~

.. code:: python

    # Python 2 only:
    for i in xrange(10**8):
        ...
.. code:: python

    # Python 2 and 3: forward-compatible
    from builtins import range
    for i in range(10**8):
        ...
.. code:: python

    # Python 2 and 3: backward-compatible
    from past.builtins import xrange
    for i in xrange(10**8):
        ...
range
~~~~~

.. code:: python

    # Python 2 only
    mylist = range(5)
    assert mylist == [0, 1, 2, 3, 4]
.. code:: python

    # Python 2 and 3: forward-compatible: option 1
    mylist = list(range(5))            # copies memory on Py2
    assert mylist == [0, 1, 2, 3, 4]
.. code:: python

    # Python 2 and 3: forward-compatible: option 2
    from builtins import range

    mylist = list(range(5))
    assert mylist == [0, 1, 2, 3, 4]
.. code:: python

    # Python 2 and 3: option 3
    from future.utils import lrange

    mylist = lrange(5)
    assert mylist == [0, 1, 2, 3, 4]
.. code:: python

    # Python 2 and 3: backward compatible
    from past.builtins import range

    mylist = range(5)
    assert mylist == [0, 1, 2, 3, 4]
map
~~~

.. code:: python

    # Python 2 only:
    mynewlist = map(f, myoldlist)
    assert mynewlist == [f(x) for x in myoldlist]
.. code:: python

    # Python 2 and 3: option 1
    # Idiomatic Py3, but inefficient on Py2
    mynewlist = list(map(f, myoldlist))
    assert mynewlist == [f(x) for x in myoldlist]
.. code:: python

    # Python 2 and 3: option 2
    from builtins import map

    mynewlist = list(map(f, myoldlist))
    assert mynewlist == [f(x) for x in myoldlist]
.. code:: python

    # Python 2 and 3: option 3
    try:
        import itertools.imap as map
    except ImportError:
        pass

    mynewlist = list(map(f, myoldlist))    # inefficient on Py2
    assert mynewlist == [f(x) for x in myoldlist]
.. code:: python

    # Python 2 and 3: option 4
    from future.utils import lmap

    mynewlist = lmap(f, myoldlist)
    assert mynewlist == [f(x) for x in myoldlist]
.. code:: python

    # Python 2 and 3: option 5
    from past.builtins import map

    mynewlist = map(f, myoldlist)
    assert mynewlist == [f(x) for x in myoldlist]
imap
~~~~

.. code:: python

    # Python 2 only:
    from itertools import imap

    myiter = imap(func, myoldlist)
    assert isinstance(myiter, iter)
.. code:: python

    # Python 3 only:
    myiter = map(func, myoldlist)
    assert isinstance(myiter, iter)
.. code:: python

    # Python 2 and 3: option 1
    from builtins import map

    myiter = map(func, myoldlist)
    assert isinstance(myiter, iter)
.. code:: python

    # Python 2 and 3: option 2
    try:
        import itertools.imap as map
    except ImportError:
        pass

    myiter = map(func, myoldlist)
    assert isinstance(myiter, iter)
.. code:: python

    # Python 2 and 3: option 3
    from six.moves import map

    myiter = map(func, myoldlist)
    assert isinstance(myiter, iter)

zip, izip
~~~~~~~~~

As above with ``zip`` and ``itertools.izip``.

filter, ifilter
~~~~~~~~~~~~~~~

As above with ``filter`` and ``itertools.ifilter`` too.

Other builtins
--------------

File IO with open()
~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only
    f = open('myfile.txt')
    data = f.read()              # as a byte string
    text = data.decode('utf-8')

    # Python 2 and 3: alternative 1
    from io import open
    f = open('myfile.txt', 'rb')
    data = f.read()              # as bytes
    text = data.decode('utf-8')  # unicode, not bytes

    # Python 2 and 3: alternative 2
    from io import open
    f = open('myfile.txt', encoding='utf-8')
    text = f.read()    # unicode, not bytes
reduce()
~~~~~~~~

.. code:: python

    # Python 2 only:
    assert reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) == 1+2+3+4+5
.. code:: python

    # Python 2 and 3:
    from functools import reduce

    assert reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) == 1+2+3+4+5
raw\_input()
~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    name = raw_input('What is your name? ')
    assert isinstance(name, str)    # native str
.. code:: python

    # Python 2 and 3:
    from builtins import input

    name = input('What is your name? ')
    assert isinstance(name, str)    # native str on Py2 and Py3
input()
~~~~~~~

.. code:: python

    # Python 2 only:
    input("Type something safe please: ")
.. code:: python

    # Python 2 and 3
    from builtins import input
    eval(input("Type something safe please: "))
Warning: using either of these is **unsafe** with untrusted input.

file()
~~~~~~

.. code:: python

    # Python 2 only:
    f = file(pathname)
.. code:: python

    # Python 2 and 3:
    f = open(pathname)

    # But preferably, use this:
    from io import open
    f = open(pathname, 'rb')   # if f.read() should return bytes
    # or
    f = open(pathname, 'rt')   # if f.read() should return unicode text
exec
~~~~

.. code:: python

    # Python 2 only:
    exec 'x = 10'

    # Python 2 and 3:
    exec('x = 10')
.. code:: python

    # Python 2 only:
    g = globals()
    exec 'x = 10' in g

    # Python 2 and 3:
    g = globals()
    exec('x = 10', g)
.. code:: python

    # Python 2 only:
    l = locals()
    exec 'x = 10' in g, l

    # Python 2 and 3:
    exec('x = 10', g, l)
execfile()
~~~~~~~~~~

.. code:: python

    # Python 2 only:
    execfile('myfile.py')
.. code:: python

    # Python 2 and 3: alternative 1
    from past.builtins import execfile

    execfile('myfile.py')
.. code:: python

    # Python 2 and 3: alternative 2
    exec(compile(open('myfile.py').read()))

    # This can sometimes cause this:
    #     SyntaxError: function ... uses import * and bare exec ...
    # See https://github.com/PythonCharmers/python-future/issues/37
unichr()
~~~~~~~~

.. code:: python

    # Python 2 only:
    assert unichr(8364) == '€'
.. code:: python

    # Python 3 only:
    assert chr(8364) == '€'
.. code:: python

    # Python 2 and 3:
    from builtins import chr
    assert chr(8364) == '€'
intern()
~~~~~~~~

.. code:: python

    # Python 2 only:
    intern('mystring')
.. code:: python

    # Python 3 only:
    from sys import intern
    intern('mystring')
.. code:: python

    # Python 2 and 3: alternative 1
    from past.builtins import intern
    intern('mystring')
.. code:: python

    # Python 2 and 3: alternative 2
    from six.moves import intern
    intern('mystring')
.. code:: python

    # Python 2 and 3: alternative 3
    from future.standard_library import install_aliases
    install_aliases()
    from sys import intern
    intern('mystring')
.. code:: python

    # Python 2 and 3: alternative 2
    try:
        from sys import intern
    except ImportError:
        pass
    intern('mystring')
apply()
~~~~~~~

.. code:: python

    args = ('a', 'b')
    kwargs = {'kwarg1': True}
.. code:: python

    # Python 2 only:
    apply(f, args, kwargs)
.. code:: python

    # Python 2 and 3: alternative 1
    f(*args, **kwargs)
.. code:: python

    # Python 2 and 3: alternative 2
    from past.builtins import apply
    apply(f, args, kwargs)
chr()
~~~~~

.. code:: python

    # Python 2 only:
    assert chr(64) == b'@'
    assert chr(200) == b'\xc8'
.. code:: python

    # Python 3 only: option 1
    assert chr(64).encode('latin-1') == b'@'
    assert chr(0xc8).encode('latin-1') == b'\xc8'
.. code:: python

    # Python 2 and 3: option 1
    from builtins import chr

    assert chr(64).encode('latin-1') == b'@'
    assert chr(0xc8).encode('latin-1') == b'\xc8'
.. code:: python

    # Python 3 only: option 2
    assert bytes([64]) == b'@'
    assert bytes([0xc8]) == b'\xc8'
.. code:: python

    # Python 2 and 3: option 2
    from builtins import bytes

    assert bytes([64]) == b'@'
    assert bytes([0xc8]) == b'\xc8'
cmp()
~~~~~

.. code:: python

    # Python 2 only:
    assert cmp('a', 'b') < 0 and cmp('b', 'a') > 0 and cmp('c', 'c') == 0
.. code:: python

    # Python 2 and 3: alternative 1
    from past.builtins import cmp
    assert cmp('a', 'b') < 0 and cmp('b', 'a') > 0 and cmp('c', 'c') == 0
.. code:: python

    # Python 2 and 3: alternative 2
    cmp = lambda(x, y): (x > y) - (x < y)
    assert cmp('a', 'b') < 0 and cmp('b', 'a') > 0 and cmp('c', 'c') == 0
reload()
~~~~~~~~

.. code:: python

    # Python 2 only:
    reload(mymodule)
.. code:: python

    # Python 2 and 3
    from imp import reload
    reload(mymodule)
Standard library
----------------

dbm modules
~~~~~~~~~~~

.. code:: python

    # Python 2 only
    import anydbm
    import whichdb
    import dbm
    import dumbdbm
    import gdbm

    # Python 2 and 3: alternative 1
    from future import standard_library
    standard_library.install_aliases()

    import dbm
    import dbm.ndbm
    import dbm.dumb
    import dbm.gnu

    # Python 2 and 3: alternative 2
    from future.moves import dbm
    from future.moves.dbm import dumb
    from future.moves.dbm import ndbm
    from future.moves.dbm import gnu

    # Python 2 and 3: alternative 3
    from six.moves import dbm_gnu
    # (others not supported)
commands / subprocess modules
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only
    from commands import getoutput, getstatusoutput

    # Python 2 and 3
    from future import standard_library
    standard_library.install_aliases()

    from subprocess import getoutput, getstatusoutput
StringIO module
~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only
    from StringIO import StringIO
    from cStringIO import StringIO
.. code:: python

    # Python 2 and 3
    from io import BytesIO
    # and refactor StringIO() calls to BytesIO() if passing byte-strings
http module
~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    import httplib
    import Cookie
    import cookielib
    import BaseHTTPServer
    import SimpleHTTPServer
    import CGIHttpServer

    # Python 2 and 3 (after ``pip install future``):
    import http.client
    import http.cookies
    import http.cookiejar
    import http.server
xmlrpc module
~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    import DocXMLRPCServer
    import SimpleXMLRPCServer

    # Python 2 and 3 (after ``pip install future``):
    import xmlrpc.server
.. code:: python

    # Python 2 only:
    import xmlrpclib

    # Python 2 and 3 (after ``pip install future``):
    import xmlrpc.client
html escaping and entities
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 and 3:
    from cgi import escape

    # Safer (Python 2 and 3, after ``pip install future``):
    from html import escape

    # Python 2 only:
    from htmlentitydefs import codepoint2name, entitydefs, name2codepoint

    # Python 2 and 3 (after ``pip install future``):
    from html.entities import codepoint2name, entitydefs, name2codepoint
html parsing
~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    from HTMLParser import HTMLParser

    # Python 2 and 3 (after ``pip install future``)
    from html.parser import HTMLParser

    # Python 2 and 3 (alternative 2):
    from future.moves.html.parser import HTMLParser
urllib module
~~~~~~~~~~~~~

``urllib`` is the hardest module to use from Python 2/3 compatible code.
You might want to switch to Requests (http://python-requests.org) instead.

.. code:: python

    # Python 2 only:
    from urlparse import urlparse
    from urllib import urlencode
    from urllib2 import urlopen, Request, HTTPError
.. code:: python

    # Python 3 only:
    from urllib.parse import urlparse, urlencode
    from urllib.request import urlopen, Request
    from urllib.error import HTTPError
.. code:: python

    # Python 2 and 3: easiest option
    from future.standard_library import install_aliases
    install_aliases()

    from urllib.parse import urlparse, urlencode
    from urllib.request import urlopen, Request
    from urllib.error import HTTPError
.. code:: python

    # Python 2 and 3: alternative 2
    from future.standard_library import hooks

    with hooks():
        from urllib.parse import urlparse, urlencode
        from urllib.request import urlopen, Request
        from urllib.error import HTTPError
.. code:: python

    # Python 2 and 3: alternative 3
    from future.moves.urllib.parse import urlparse, urlencode
    from future.moves.urllib.request import urlopen, Request
    from future.moves.urllib.error import HTTPError
    # or
    from six.moves.urllib.parse import urlparse, urlencode
    from six.moves.urllib.request import urlopen
    from six.moves.urllib.error import HTTPError
.. code:: python

    # Python 2 and 3: alternative 4
    try:
        from urllib.parse import urlparse, urlencode
        from urllib.request import urlopen, Request
        from urllib.error import HTTPError
    except ImportError:
        from urlparse import urlparse
        from urllib import urlencode
        from urllib2 import urlopen, Request, HTTPError
Tkinter
~~~~~~~

.. code:: python

    # Python 2 only:
    import Tkinter
    import Dialog
    import FileDialog
    import ScrolledText
    import SimpleDialog
    import Tix
    import Tkconstants
    import Tkdnd
    import tkColorChooser
    import tkCommonDialog
    import tkFileDialog
    import tkFont
    import tkMessageBox
    import tkSimpleDialog
    import ttk

    # Python 2 and 3 (after ``pip install future``):
    import tkinter
    import tkinter.dialog
    import tkinter.filedialog
    import tkinter.scrolledtext
    import tkinter.simpledialog
    import tkinter.tix
    import tkinter.constants
    import tkinter.dnd
    import tkinter.colorchooser
    import tkinter.commondialog
    import tkinter.filedialog
    import tkinter.font
    import tkinter.messagebox
    import tkinter.simpledialog
    import tkinter.ttk
socketserver
~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    import SocketServer

    # Python 2 and 3 (after ``pip install future``):
    import socketserver
copy\_reg, copyreg
~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    import copy_reg

    # Python 2 and 3 (after ``pip install future``):
    import copyreg
configparser
~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    from ConfigParser import ConfigParser

    # Python 2 and 3 (after ``pip install configparser``):
    from configparser import ConfigParser
queue
~~~~~

.. code:: python

    # Python 2 only:
    from Queue import Queue, heapq, deque

    # Python 2 and 3 (after ``pip install future``):
    from queue import Queue, heapq, deque
repr, reprlib
~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    from repr import aRepr, repr

    # Python 2 and 3 (after ``pip install future``):
    from reprlib import aRepr, repr
UserDict, UserList, UserString
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    from UserDict import UserDict
    from UserList import UserList
    from UserString import UserString

    # Python 3 only:
    from collections import UserDict, UserList, UserString

    # Python 2 and 3: alternative 1
    from future.moves.collections import UserDict, UserList, UserString

    # Python 2 and 3: alternative 2
    from six.moves import UserDict, UserList, UserString

    # Python 2 and 3: alternative 3
    from future.standard_library import install_aliases
    install_aliases()
    from collections import UserDict, UserList, UserString
itertools: filterfalse, zip\_longest
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    # Python 2 only:
    from itertools import ifilterfalse, izip_longest

    # Python 3 only:
    from itertools import filterfalse, zip_longest

    # Python 2 and 3: alternative 1
    from future.moves.itertools import filterfalse, zip_longest

    # Python 2 and 3: alternative 2
    from six.moves import filterfalse, zip_longest

    # Python 2 and 3: alternative 3
    from future.standard_library import install_aliases
    install_aliases()
    from itertools import filterfalse, zip_longest