README.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. .. _overview:
  2. Overview: Easy, clean, reliable Python 2/3 compatibility
  3. ========================================================
  4. .. image:: https://travis-ci.org/PythonCharmers/python-future.svg?branch=master
  5. :target: https://travis-ci.org/PythonCharmers/python-future
  6. .. image:: https://readthedocs.org/projects/python-future/badge/?version=latest
  7. :target: https://python-future.readthedocs.io/en/latest/?badge=latest
  8. ``python-future`` is the missing compatibility layer between Python 2 and
  9. Python 3. It allows you to use a single, clean Python 3.x-compatible
  10. codebase to support both Python 2 and Python 3 with minimal overhead.
  11. It provides ``future`` and ``past`` packages with backports and forward
  12. ports of features from Python 3 and 2. It also comes with ``futurize`` and
  13. ``pasteurize``, customized 2to3-based scripts that helps you to convert
  14. either Py2 or Py3 code easily to support both Python 2 and 3 in a single
  15. clean Py3-style codebase, module by module.
  16. Notable projects that use ``python-future`` for Python 2/3 compatibility
  17. are `Mezzanine <http://mezzanine.jupo.org/>`_ and `ObsPy
  18. <http://obspy.org>`_.
  19. .. _features:
  20. Features
  21. --------
  22. - ``future.builtins`` package (also available as ``builtins`` on Py2) provides
  23. backports and remappings for 20 builtins with different semantics on Py3
  24. versus Py2
  25. - support for directly importing 30 standard library modules under
  26. their Python 3 names on Py2
  27. - support for importing the other 14 refactored standard library modules
  28. under their Py3 names relatively cleanly via
  29. ``future.standard_library`` and ``future.moves``
  30. - ``past.builtins`` package provides forward-ports of 19 Python 2 types and
  31. builtin functions. These can aid with per-module code migrations.
  32. - ``past.translation`` package supports transparent translation of Python 2
  33. modules to Python 3 upon import. [This feature is currently in alpha.]
  34. - 1000+ unit tests, including many from the Py3.3 source tree.
  35. - ``futurize`` and ``pasteurize`` scripts based on ``2to3`` and parts of
  36. ``3to2`` and ``python-modernize``, for automatic conversion from either Py2
  37. or Py3 to a clean single-source codebase compatible with Python 2.6+ and
  38. Python 3.3+.
  39. - a curated set of utility functions and decorators in ``future.utils`` and
  40. ``past.utils`` selected from Py2/3 compatibility interfaces from projects
  41. like ``six``, ``IPython``, ``Jinja2``, ``Django``, and ``Pandas``.
  42. - support for the ``surrogateescape`` error handler when encoding and
  43. decoding the backported ``str`` and ``bytes`` objects. [This feature is
  44. currently in alpha.]
  45. - support for pre-commit hooks
  46. .. _code-examples:
  47. Code examples
  48. -------------
  49. Replacements for Py2's built-in functions and types are designed to be imported
  50. at the top of each Python module together with Python's built-in ``__future__``
  51. statements. For example, this code behaves identically on Python 2.6/2.7 after
  52. these imports as it does on Python 3.3+:
  53. .. code-block:: python
  54. from __future__ import absolute_import, division, print_function
  55. from builtins import (bytes, str, open, super, range,
  56. zip, round, input, int, pow, object)
  57. # Backported Py3 bytes object
  58. b = bytes(b'ABCD')
  59. assert list(b) == [65, 66, 67, 68]
  60. assert repr(b) == "b'ABCD'"
  61. # These raise TypeErrors:
  62. # b + u'EFGH'
  63. # bytes(b',').join([u'Fred', u'Bill'])
  64. # Backported Py3 str object
  65. s = str(u'ABCD')
  66. assert s != bytes(b'ABCD')
  67. assert isinstance(s.encode('utf-8'), bytes)
  68. assert isinstance(b.decode('utf-8'), str)
  69. assert repr(s) == "'ABCD'" # consistent repr with Py3 (no u prefix)
  70. # These raise TypeErrors:
  71. # bytes(b'B') in s
  72. # s.find(bytes(b'A'))
  73. # Extra arguments for the open() function
  74. f = open('japanese.txt', encoding='utf-8', errors='replace')
  75. # New zero-argument super() function:
  76. class VerboseList(list):
  77. def append(self, item):
  78. print('Adding an item')
  79. super().append(item)
  80. # New iterable range object with slicing support
  81. for i in range(10**15)[:10]:
  82. pass
  83. # Other iterators: map, zip, filter
  84. my_iter = zip(range(3), ['a', 'b', 'c'])
  85. assert my_iter != list(my_iter)
  86. # The round() function behaves as it does in Python 3, using
  87. # "Banker's Rounding" to the nearest even last digit:
  88. assert round(0.1250, 2) == 0.12
  89. # input() replaces Py2's raw_input() (with no eval()):
  90. name = input('What is your name? ')
  91. print('Hello ' + name)
  92. # pow() supports fractional exponents of negative numbers like in Py3:
  93. z = pow(-1, 0.5)
  94. # Compatible output from isinstance() across Py2/3:
  95. assert isinstance(2**64, int) # long integers
  96. assert isinstance(u'blah', str)
  97. assert isinstance('blah', str) # only if unicode_literals is in effect
  98. # Py3-style iterators written as new-style classes (subclasses of
  99. # future.types.newobject) are automatically backward compatible with Py2:
  100. class Upper(object):
  101. def __init__(self, iterable):
  102. self._iter = iter(iterable)
  103. def __next__(self): # note the Py3 interface
  104. return next(self._iter).upper()
  105. def __iter__(self):
  106. return self
  107. assert list(Upper('hello')) == list('HELLO')
  108. There is also support for renamed standard library modules. The recommended
  109. interface works like this:
  110. .. code-block:: python
  111. # Many Py3 module names are supported directly on both Py2.x and 3.x:
  112. from http.client import HttpConnection
  113. import html.parser
  114. import queue
  115. import xmlrpc.client
  116. # Refactored modules with clashing names on Py2 and Py3 are supported
  117. # as follows:
  118. from future import standard_library
  119. standard_library.install_aliases()
  120. # Then, for example:
  121. from itertools import filterfalse, zip_longest
  122. from urllib.request import urlopen
  123. from collections import ChainMap
  124. from collections import UserDict, UserList, UserString
  125. from subprocess import getoutput, getstatusoutput
  126. from collections import Counter, OrderedDict # backported to Py2.6
  127. Automatic conversion to Py2/3-compatible code
  128. ---------------------------------------------
  129. ``python-future`` comes with two scripts called ``futurize`` and
  130. ``pasteurize`` to aid in making Python 2 code or Python 3 code compatible with
  131. both platforms (Py2/3). It is based on 2to3 and uses fixers from ``lib2to3``,
  132. ``lib3to2``, and ``python-modernize``, as well as custom fixers.
  133. ``futurize`` passes Python 2 code through all the appropriate fixers to turn it
  134. into valid Python 3 code, and then adds ``__future__`` and ``future`` package
  135. imports so that it also runs under Python 2.
  136. For conversions from Python 3 code to Py2/3, use the ``pasteurize`` script
  137. instead. This converts Py3-only constructs (e.g. new metaclass syntax) to
  138. Py2/3 compatible constructs and adds ``__future__`` and ``future`` imports to
  139. the top of each module.
  140. In both cases, the result should be relatively clean Py3-style code that runs
  141. mostly unchanged on both Python 2 and Python 3.
  142. Futurize: 2 to both
  143. ~~~~~~~~~~~~~~~~~~~
  144. For example, running ``futurize -w mymodule.py`` turns this Python 2 code:
  145. .. code-block:: python
  146. import Queue
  147. from urllib2 import urlopen
  148. def greet(name):
  149. print 'Hello',
  150. print name
  151. print "What's your name?",
  152. name = raw_input()
  153. greet(name)
  154. into this code which runs on both Py2 and Py3:
  155. .. code-block:: python
  156. from __future__ import print_function
  157. from future import standard_library
  158. standard_library.install_aliases()
  159. from builtins import input
  160. import queue
  161. from urllib.request import urlopen
  162. def greet(name):
  163. print('Hello', end=' ')
  164. print(name)
  165. print("What's your name?", end=' ')
  166. name = input()
  167. greet(name)
  168. See :ref:`forwards-conversion` and :ref:`backwards-conversion` for more details.
  169. Automatic translation
  170. ---------------------
  171. The ``past`` package can automatically translate some simple Python 2
  172. modules to Python 3 upon import. The goal is to support the "long tail" of
  173. real-world Python 2 modules (e.g. on PyPI) that have not been ported yet. For
  174. example, here is how to use a Python 2-only package called ``plotrique`` on
  175. Python 3. First install it:
  176. .. code-block:: bash
  177. $ pip3 install plotrique==0.2.5-7 --no-compile # to ignore SyntaxErrors
  178. (or use ``pip`` if this points to your Py3 environment.)
  179. Then pass a whitelist of module name prefixes to the ``autotranslate()`` function.
  180. Example:
  181. .. code-block:: bash
  182. $ python3
  183. >>> from past.translation import autotranslate
  184. >>> autotranslate(['plotrique'])
  185. >>> import plotrique
  186. This transparently translates and runs the ``plotrique`` module and any
  187. submodules in the ``plotrique`` package that ``plotrique`` imports.
  188. This is intended to help you migrate to Python 3 without the need for all
  189. your code's dependencies to support Python 3 yet. It should be used as a
  190. last resort; ideally Python 2-only dependencies should be ported
  191. properly to a Python 2/3 compatible codebase using a tool like
  192. ``futurize`` and the changes should be pushed to the upstream project.
  193. Note: the auto-translation feature is still in alpha; it needs more testing and
  194. development, and will likely never be perfect.
  195. For more info, see :ref:`translation`.
  196. Pre-commit hooks
  197. ----------------
  198. `Pre-commit <https://pre-commit.com/>`_ is a framework for managing and maintaining
  199. multi-language pre-commit hooks.
  200. In case you need to port your project from Python 2 to Python 3, you might consider
  201. using such hook during the transition period.
  202. First:
  203. .. code-block:: bash
  204. $ pip install pre-commit
  205. and then in your project's directory:
  206. .. code-block:: bash
  207. $ pre-commit install
  208. Next, you need to add this entry to your ``.pre-commit-config.yaml``
  209. .. code-block:: yaml
  210. - repo: https://github.com/PythonCharmers/python-future
  211. rev: master
  212. hooks:
  213. - id: futurize
  214. args: [--both-stages]
  215. The ``args`` part is optional, by default only stage1 is applied.
  216. Licensing
  217. ---------
  218. :Author: Ed Schofield, Jordan M. Adler, et al
  219. :Copyright: 2013-2019 Python Charmers Pty Ltd, Australia.
  220. :Sponsors: Python Charmers Pty Ltd, Australia, and Python Charmers Pte
  221. Ltd, Singapore. http://pythoncharmers.com
  222. Pinterest https://opensource.pinterest.com/
  223. :Licence: MIT. See ``LICENSE.txt`` or `here <http://python-future.org/credits.html>`_.
  224. :Other credits: See `here <http://python-future.org/credits.html>`_.
  225. Next steps
  226. ----------
  227. If you are new to Python-Future, check out the `Quickstart Guide
  228. <http://python-future.org/quickstart.html>`_.
  229. For an update on changes in the latest version, see the `What's New
  230. <http://python-future.org/whatsnew.html>`_ page.