Python 2-to-3 Cheat Sheet
A short reference of new Python 3 features.
Python 3.4
- PEP 446: Newly created file descriptors non-inheritable by default.
min(..., default=...)andmax(..., default=...).asyncio. Status: Provisional.enum.pathlib. Status: Provisional.
Python 3.3
yield fromstatement:- Receive sent and thrown values from the calling scope.
- Return value to the outer generator.
venvmodule andpyvenvscript.raise exc from Noneto suppress exception context.collections.ChainMap.
Python 3.2
optparseargparse.str.format_map().@functools.lru_cache(maxsize=...).@functools.total_ordering.collection.OrderedDict.move_to_end(key, last=True).threading.Barrier.io.BytesIO.getbuffer()returns an editable view of the internal data.@reprlib.recursive_repr()for recursive structure.with subprocess.Popen(...).with tempfile.TemporaryDirectory().
Python 3.1
collections.OrderedDict, which is also used byconfigparser,collections.namedtuple,json, etc.collections.Counter.format(1234567.89, ',.2f') == '1,234,567.89'.n.bit_length().- Multiple context managers:
with open('input') as infile, open('output', 'w') as outfile:collections.namedtuple(..., rename=False).logging.NullHandler.importlib.
Python 3.0
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False).exec()is a function.dict.keys(),dict.items(), anddict.values()return views.dict.iterkeys()dict.iteritems()dict.itervalues()map()andfilter()return iterators.map()stops when the shortest iterator is exhausted.xrange()range().zip()returns an iterator.- You cannot make comparison of
None < None,1 < '', etc. list.sort()andsorted():cmpkey.object.__cmp__().longint.1 / 2 == 0.5and4 // 2 == 1.sys.maxintsys.maxsize(since “maxint” makes not sense anymore).- Octal literal:
0o720. No0720anymore.oct(16) == '0o20'. - Binary literal:
0b101.bin(8) == '0b1000'. stris a sequence of Unicode code points.str(byte_string, encoding=...)vsbytes(text_string, encoding=...).'Unicode string literal'vsb'byte string literal'.(since there is notbasestringunicodeandstrnow).- Remember to pass
encodingtoopen(..., encoding=None, ...)when opening in text mode. sys.stdinet al. are now Unicode-only text files (io.TextIOBase). Useio.TextIOBase.buferfor byte data.- File names and paths are now Unicode strings, but:
- Some APIs accept byte strings, too.
- Some APIs return byte strings when passing in byte strings, too.
os.environ,sys.argv, etc. might not be interpretable using the current encoding.StringIOcStringIOio.StringIOandio.BytesIO.- PEP 3107: Argument and return value annotations.
# func.__annotations__ == {'return': 'world', 'arg': 'hello'}
def func(arg: 'hello') -> 'world':
pass- PEP 3102: Keyword-only arguments.
# Not required to have a default value.
def func(*args, keyword_only):
pass
def func(*, keyword_only):
pass- PEP 3104:
nonlocal, lexical scoping. - PEP 3132:
a, b, *rest = any_iterableor*rest, c = stuff. - PEP 0274: Dictionary comprehensions
{k : v for k, v in stuff}and set comprehensions{e for e in stuff}. - Set literal
{1, 2}.{}is an empty dictionary. - PEP 3109 and PEP 3134: Exception chaining:
# Re-raise the active exception.
raise
# Implicit exception chaining.
# e.__context__
raise E(V)
# Explicit exception chaining.
# e.__cause__ == C
raise E(V) from CTrue,False, andNoneare reserved words.except exc as var.object.__metaclass__class C(metaclass=M).- Ellipsis
...is a built-in constant. - Classic classes are gone.
- All import forms not starting with
.are interpreted as absolute imports. - PEP 3129: Class decorators.
