__future__ nested_scopes PEP 227: Statically Nested Scopes generators PEP 255: Simple Generators division PEP 238: Changing the Division Operator absolute_import PEP 328: Imports: Multi-Line and Absolute/Relative with_statement PEP 343: The “with” Statement print_function PEP 3105: Make print a function unicode_literals PEP 3112: Bytes literals in Python 3000 https://docs.python.org/2.7/library/__future__.html
six Renamed modules and attributes compatibility ● six.moves Name Python 2 name Python 3 name html_parser HTMLParser html.parser >>> from six.moves import html_parser https://pypi.python.org/pypi/six
six Binary and text data ● six.b(data) ● six.u(text) ● six.StringIO ● six.BytesIO ● @six.python_2_unicode_compatible ● ... https://pypi.python.org/pypi/six
six Django Support ● A customized version of six is bundled with Django as of version 1.4.2. ● django.utils.six https://docs.djangoproject.com/en/1.10/topics/python3/#writing-compatible-code-with-six
future ● future.builtins ● past.builtins ● future.standard_library and future.moves ● futurize and pasteurize ● Support for directly importing 30 standard library modules under their Python 3 names on Python 2 https://pypi.python.org/pypi/future
Writing Python 2-3 compatible code ● Only worry about supporting Python 2.7 ● Using __future__ ● Make sure you have good test coverage ● Use pylint to help make sure you don’t regress on your Python 3 support ● Use caniusepython3 to find out which of your dependencies are blocking Python 3 ● tox can help test against multiple versions of Python ● Use 2to3 to rewrite your code to run only under Python 3
print # Python 2 only: print 'Hello' # Python 2 and 3: print('Hello') # Python 2 and 3: from __future__ import print_function # at top of module print('Hello', 'Guido')
Dictionaries # Python 2 only: for value in heights.itervalues(): ... # Idiomatic Python 3 for value in heights.values(): # extra memory overhead on Py2 ... # Python 2 and 3: option 2 from six import itervalues for key in itervalues(heights): ...
Dictionaries # Python 2 only: for (key, value) in heights.iteritems(): ... # Python 2 and 3: option 1 for (key, value) in heights.items(): # inefficient on Py2 ... # Python 2 and 3: option 3 from six import iteritems for (key, value) in iteritems(heights): ...
References ● “Supporting Python 3: An in-depth guide” Lennart Regebro ● “Dive Into Python 3” Appendix A: Porting Code to Python 3 using 2to3 Mark Pilgrim