GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing python-future.org — Overview: Easy, clean, reliable Python 2/3 compatibility — Python-Future documentation Overview: Easy, clean, reliable Python 2/3 compatibility¶
It provides The Status¶The That time is now past. Thanks to a huge porting effort across the Python
community, Python 3 eventually thrived. Python 2 reached its end of life in
2020 and the Features¶
Code examples¶Replacements for Py2’s built-in functions and types are designed to be imported
at the top of each Python module together with Python’s built-in from __future__ import absolute_import, division, print_function from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object) # Backported Py3 bytes object b = bytes(b'ABCD') assert list(b) == [65, 66, 67, 68] assert repr(b) == "b'ABCD'" # These raise TypeErrors: # b + u'EFGH' # bytes(b',').join([u'Fred', u'Bill']) # Backported Py3 str object s = str(u'ABCD') assert s != bytes(b'ABCD') assert isinstance(s.encode('utf-8'), bytes) assert isinstance(b.decode('utf-8'), str) assert repr(s) == "'ABCD'" # consistent repr with Py3 (no u prefix) # These raise TypeErrors: # bytes(b'B') in s # s.find(bytes(b'A')) # Extra arguments for the open() function f = open('japanese.txt', encoding='utf-8', errors='replace') # New zero-argument super() function: class VerboseList(list): def append(self, item): print('Adding an item') super().append(item) # New iterable range object with slicing support for i in range(10**15)[:10]: pass # Other iterators: map, zip, filter my_iter = zip(range(3), ['a', 'b', 'c']) assert my_iter != list(my_iter) # The round() function behaves as it does in Python 3, using # "Banker's Rounding" to the nearest even last digit: assert round(0.1250, 2) == 0.12 # input() replaces Py2's raw_input() (with no eval()): name = input('What is your name? ') print('Hello ' + name) # pow() supports fractional exponents of negative numbers like in Py3: z = pow(-1, 0.5) # Compatible output from isinstance() across Py2/3: assert isinstance(2**64, int) # long integers assert isinstance(u'blah', str) assert isinstance('blah', str) # only if unicode_literals is in effect # Py3-style iterators written as new-style classes (subclasses of # future.types.newobject) are automatically backward compatible with Py2: class Upper(object): def __init__(self, iterable): self._iter = iter(iterable) def __next__(self): # note the Py3 interface return next(self._iter).upper() def __iter__(self): return self assert list(Upper('hello')) == list('HELLO') There is also support for renamed standard library modules. The recommended interface works like this: # Many Py3 module names are supported directly on both Py2.x and 3.x: from http.client import HttpConnection import html.parser import queue import xmlrpc.client # Refactored modules with clashing names on Py2 and Py3 are supported # as follows: from future import standard_library standard_library.install_aliases() # Then, for example: from itertools import filterfalse, zip_longest from urllib.request import urlopen from collections import ChainMap from collections import UserDict, UserList, UserString from subprocess import getoutput, getstatusoutput from collections import Counter, OrderedDict # backported to Py2.6 Automatic conversion to Py2/3-compatible code¶
For conversions from Python 3 code to Py2/3, use the In both cases, the result should be relatively clean Py3-style code that runs mostly unchanged on both Python 2 and Python 3. Futurize: 2 to both¶For example, running import Queue from urllib2 import urlopen def greet(name): print 'Hello', print name print "What's your name?", name = raw_input() greet(name) into this code which runs on both Py2 and Py3: from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import input import queue from urllib.request import urlopen def greet(name): print('Hello', end=' ') print(name) print("What's your name?", end=' ') name = input() greet(name) The first four lines have no effect under Python 3 and can be removed from the codebase when Python 2 compatibility is no longer required. See futurize: Py2 to Py2/3 and pasteurize: Py3 to Py2/3 for more details. Automatic translation¶The $ pip3 install plotrique==0.2.5-7 --no-compile # to ignore SyntaxErrors (or use Then pass a whitelist of module name prefixes to the $ python3 >>> from past.translation import autotranslate >>> autotranslate(['plotrique']) >>> import plotrique This transparently translates and runs the This is intended to help you migrate to Python 3 without the need for all
your code’s dependencies to support Python 3 yet. It should be used as a
last resort; ideally Python 2-only dependencies should be ported
properly to a Python 2/3 compatible codebase using a tool like
Note: the auto-translation feature is still in alpha; it needs more testing and development, and will likely never be perfect. Pre-commit hooks¶Pre-commit is a framework for managing and maintaining multi-language pre-commit hooks. In case you need to port your project from Python 2 to Python 3, you might consider using such hook during the transition period. First: $ pip install pre-commit and then in your project’s directory: $ pre-commit install Next, you need to add this entry to your - repo: https://github.com/PythonCharmers/python-future rev: master hooks: - id: futurize args: [--both-stages] The Licensing¶
Docs¶See the docs here. Next steps¶If you are new to Python-Future, check out the Quickstart Guide. For an update on changes in the latest version, see the What’s New page. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |