API Reference (in progress)¶
NOTE: This page is still a work in progress… We need to go through our docstrings and make them sphinx-compliant, and figure out how to improve formatting with the sphinx-bootstrap-theme plugin. Pull requests would be very welcome.
future.builtins Interface¶
A module that brings in equivalents of the new and modified Python 3 builtins into Py2. Has no effect on Py3.
See the docs here
(docs/what-else.rst) for more information.
Backported types from Python 3¶
This module contains backports the data types that were significantly changed in the transition from Python 2 to Python 3.
an implementation of Python 3’s bytes object (pure Python subclass of Python 2’s builtin 8-bit str type)
an implementation of Python 3’s str object (pure Python subclass of Python 2’s builtin unicode type)
a backport of the range iterator from Py3 with slicing support
It is used as follows:
from __future__ import division, absolute_import, print_function
from builtins import bytes, dict, int, range, str
to bring in the new semantics for these functions from Python 3. And then, for example:
b = bytes(b'ABCD')
assert list(b) == [65, 66, 67, 68]
assert repr(b) == "b'ABCD'"
assert [65, 66] in b
# These raise TypeErrors:
# b + u'EFGH'
# b.split(u'B')
# bytes(b',').join([u'Fred', u'Bill'])
s = str(u'ABCD')
# These raise TypeErrors:
# s.join([b'Fred', b'Bill'])
# s.startswith(b'A')
# b'B' in s
# s.find(b'A')
# s.replace(u'A', b'a')
# This raises an AttributeError:
# s.decode('utf-8')
assert repr(s) == 'ABCD' # consistent repr with Py3 (no u prefix)
for i in range(10**11)[:10]:
pass
and:
class VerboseList(list):
def append(self, item):
print('Adding an item')
super().append(item) # new simpler super() function
For more information:¶
future.types.newbytes
future.types.newdict
future.types.newint
future.types.newobject
future.types.newrange
future.types.newstr
Notes¶
range()¶
range is a custom class that backports the slicing behaviour from
Python 3 (based on the xrange module by Dan Crosta). See the
newrange module docstring for more details.
super()¶
super() is based on Ryan Kelly’s magicsuper module. See the
newsuper module docstring for more details.
round()¶
Python 3 modifies the behaviour of round() to use “Banker’s Rounding”.
See http://stackoverflow.com/a/10825998. See the newround module
docstring for more details.
future.standard_library Interface¶
Python 3 reorganized the standard library (PEP 3108). This module exposes several standard library modules to Python 2 under their new Python 3 names.
It is designed to be used as follows:
from future import standard_library
standard_library.install_aliases()
And then these normal Py3 imports work on both Py3 and Py2:
import builtins
import copyreg
import queue
import reprlib
import socketserver
import winreg # on Windows only
import test.support
import html, html.parser, html.entities
import http, http.client, http.server
import http.cookies, http.cookiejar
import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
import xmlrpc.client, xmlrpc.server
import _thread
import _dummy_thread
import _markupbase
from itertools import filterfalse, zip_longest
from sys import intern
from collections import UserDict, UserList, UserString
from collections import OrderedDict, Counter, ChainMap # even on Py2.6
from subprocess import getoutput, getstatusoutput
from subprocess import check_output # even on Py2.6
(The renamed modules and functions are still available under their old names on Python 2.)
This is a cleaner alternative to this idiom (see http://docs.pythonsprints.com/python3_porting/py-porting.html):
try:
import queue
except ImportError:
import Queue as queue
Limitations¶
We don’t currently support these modules, but would like to:
import dbm
import dbm.dumb
import dbm.gnu
import collections.abc # on Py33
import pickle # should (optionally) bring in cPickle on Python 2
- class future.standard_library.RenameImport(old_to_new)[source]¶
A class for import hooks mapping Py3 module names etc. to the Py2 equivalents.
- future.standard_library.cache_py2_modules()[source]¶
Currently this function is unneeded, as we are not attempting to provide import hooks for modules with ambiguous names: email, urllib, pickle.
- future.standard_library.detect_hooks()[source]¶
Returns True if the import hooks are installed, False if not.
- future.standard_library.disable_hooks()[source]¶
Deprecated. Use remove_hooks() instead. This will be removed by
futurev1.0.
- future.standard_library.enable_hooks()[source]¶
Deprecated. Use install_hooks() instead. This will be removed by
futurev1.0.
- class future.standard_library.exclude_local_folder_imports(*args)[source]¶
A context-manager that prevents standard library modules like configparser from being imported from the local python-future source folder on Py3.
(This was need prior to v0.16.0 because the presence of a configparser folder would otherwise have prevented setuptools from running on Py3. Maybe it’s not needed any more?)
- future.standard_library.from_import(module_name, *symbol_names, **kwargs)[source]¶
- Example use:
>>> HTTPConnection = from_import('http.client', 'HTTPConnection') >>> HTTPServer = from_import('http.server', 'HTTPServer') >>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')
Equivalent to this on Py3:
>>> from module_name import symbol_names[0], symbol_names[1], ...
and this on Py2:
>>> from future.moves.module_name import symbol_names[0], ...
or:
>>> from future.backports.module_name import symbol_names[0], ...
except that it also handles dotted module names such as
http.client.
- class future.standard_library.hooks[source]¶
Acts as a context manager. Saves the state of sys.modules and restores it after the ‘with’ block.
Use like this:
>>> from future import standard_library >>> with standard_library.hooks(): ... import http.client >>> import requests
For this to work, http.client will be scrubbed from sys.modules after the ‘with’ block. That way the modules imported in the ‘with’ block will continue to be accessible in the current namespace but not from any imported modules (like requests).
- future.standard_library.import_(module_name, backport=False)[source]¶
Pass a (potentially dotted) module name of a Python 3 standard library module. This function imports the module compatibly on Py2 and Py3 and returns the top-level module.
- Example use:
>>> http = import_('http.client') >>> http = import_('http.server') >>> urllib = import_('urllib.request')
- Then:
>>> conn = http.client.HTTPConnection(...) >>> response = urllib.request.urlopen('http://mywebsite.com') >>> # etc.
- Use as follows:
>>> package_name = import_(module_name)
On Py3, equivalent to this:
>>> import module_name
On Py2, equivalent to this if backport=False:
>>> from future.moves import module_name
or to this if backport=True:
>>> from future.backports import module_name
except that it also handles dotted module names such as
http.clientThe effect then is like this:>>> from future.backports import module >>> from future.backports.module import submodule >>> module.submodule = submodule
Note that this would be a SyntaxError in Python:
>>> from future.backports import http.client
- future.standard_library.install_aliases()[source]¶
Monkey-patches the standard library in Py2.6/7 to provide aliases for better Py3 compatibility.
- future.standard_library.install_hooks()[source]¶
This function installs the future.standard_library import hook into sys.meta_path.
- future.standard_library.is_py2_stdlib_module(m)[source]¶
Tries to infer whether the module m is from the Python 2 standard library. This may not be reliable on all systems.
- future.standard_library.remove_hooks(scrub_sys_modules=False)[source]¶
This function removes the import hook from sys.meta_path.
- future.standard_library.restore_sys_modules(scrubbed)[source]¶
Add any previously scrubbed modules back to the sys.modules cache, but only if it’s safe to do so.
- future.standard_library.scrub_py2_sys_modules()[source]¶
Removes any Python 2 standard library modules from
sys.modulesthat would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email).(Note that currently import hooks are disabled for modules like these with ambiguous names anyway …)
- class future.standard_library.suspend_hooks[source]¶
Acts as a context manager. Use like this:
>>> from future import standard_library >>> standard_library.install_hooks() >>> import http.client >>> # ... >>> with standard_library.suspend_hooks(): >>> import requests # incompatible with ``future``'s standard library hooks
If the hooks were disabled before the context, they are not installed when the context is left.
future.utils Interface¶
A selection of cross-compatible functions for Python 2 and 3.
This module exports useful functions for 2/3 compatible code:
bind_method: binds functions to classes
native_str_to_bytesandbytes_to_native_str
native_str: always equal to the native platform string object (because this may be shadowed by imports from future.builtins)lists: lrange(), lmap(), lzip(), lfilter()
- iterable method compatibility:
iteritems, iterkeys, itervalues
viewitems, viewkeys, viewvalues
These use the original method if available, otherwise they use items, keys, values.
types:
text_type: unicode in Python 2, str in Python 3
string_types: basestring in Python 2, str in Python 3
binary_type: str in Python 2, bytes in Python 3
integer_types: (int, long) in Python 2, int in Python 3
class_types: (type, types.ClassType) in Python 2, type in Python 3