Python-Future
future is the missing compatibility layer between Python 2 and Python 3. It allows you to use a single, clean Python 3.x-compatible codebase to support both Python 2 and Python 3 with minimal overhead. It provides `future` and `past` packages with backports and forward ports of features from Python 3 and 2, and includes `futurize` and `pasteurize` scripts for automated code conversion. The latest version is 1.0.0, and while feature development is complete, it supports Python 3.12.
Warnings
- breaking Python 2 reached its end-of-life in 2020. While `python-future` facilitates compatibility, relying on it for actively maintained Python 2 codebases is increasingly risky due to lack of Python 2 security updates and ecosystem support.
- gotcha The `python-future` project is declared 'done' and is not recommended for new Python 3 projects. While it receives critical compatibility updates (e.g., Python 3.12 support), its primary purpose as a Python 2/3 compatibility layer means new feature development is complete. It should not be adopted as a dependency for greenfield Python 3 development.
- gotcha The `install_aliases()` function globally modifies `sys.modules` on Python 2 to map Python 3 standard library names. This can lead to unexpected behavior or conflicts if other libraries or custom import hooks make different assumptions about the module layout.
- deprecated The `past.translation` module, which offers experimental automatic translation of Python 2 modules to Python 3 upon import, is in 'alpha' status and may be unstable or imperfect. Relying on it for critical functionality is not recommended.
- gotcha HTTPS support with the `http`-based backports within `future` is limited on Python 2.x due to significant changes in SSL support in Python 3.x. Direct `http`-based backports might fail for HTTPS connections.
Install
-
pip install future -
pip install future # Requires Python >=2.6, !=3.0.*, !=3.1.*, !=3.2.*
Imports
- Builtins
from builtins import (bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip) - StandardLibraryAliases
from future.standard_library import install_aliases install_aliases()
- __future__ imports
from __future__ import (absolute_import, division, print_function, unicode_literals)
- past.builtins
from past.builtins import basestring, unicode
Quickstart
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
from future.standard_library import install_aliases
install_aliases()
# Now write Python 3 code that runs on both Py2 and Py3
print("Hello, world!")
def divide(a, b):
return a / b # Will use float division even on Python 2
my_dict = {'a': 1, 'b': 2}
print(list(my_dict.keys())) # dict.keys() returns a view (iterable) on Py2 with future installed
# Example of Python 3 library name working on Py2
import urllib.request
print(urllib.request.urlopen('http://example.com').getcode())