ITookAPill's picture
PyComp First Commit
9273228
|
Raw
History Blame Contribute Delete
113 kB

A newer version of the Gradio SDK is available: 6.22.0

Upgrade

What's New In Python 3.5

Editors : Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>

* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.

* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.

* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)

* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.

* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.

* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).

* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.

  • It's helpful to add the bug/patch number as a comment:

XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in 12345{.interpreted-text role="issue"}.)

This saves the maintainer the effort of going through the Mercurial log when researching a change.

This article explains the new features in Python 3.5, compared to 3.4. Python 3.5 was released on September 13, 2015. See the changelog for a full list of changes.

::: seealso 478{.interpreted-text role="pep"} - Python 3.5 Release Schedule :::

Summary -- Release highlights

New syntax features:

  • PEP 492 <whatsnew-pep-492>{.interpreted-text role="ref"}, coroutines with async and await syntax.
  • PEP 465 <whatsnew-pep-465>{.interpreted-text role="ref"}, a new matrix multiplication operator: a @ b.
  • PEP 448 <whatsnew-pep-448>{.interpreted-text role="ref"}, additional unpacking generalizations.

New library modules:

  • typing{.interpreted-text role="mod"}: PEP 484 -- Type Hints <whatsnew-pep-484>{.interpreted-text role="ref"}.
  • zipapp{.interpreted-text role="mod"}: PEP 441 Improving Python ZIP Application Support <whatsnew-zipapp>{.interpreted-text role="ref"}.

New built-in features:

  • bytes % args, bytearray % args: PEP 461 <whatsnew-pep-461>{.interpreted-text role="ref"} -- Adding % formatting to bytes and bytearray.
  • New bytes.hex{.interpreted-text role="meth"}, bytearray.hex{.interpreted-text role="meth"} and memoryview.hex{.interpreted-text role="meth"} methods. (Contributed by Arnon Yaari in 9951{.interpreted-text role="issue"}.)
  • memoryview{.interpreted-text role="class"} now supports tuple indexing (including multi-dimensional). (Contributed by Antoine Pitrou in 23632{.interpreted-text role="issue"}.)
  • Generators have a new gi_yieldfrom attribute, which returns the object being iterated by yield from expressions. (Contributed by Benno Leslie and Yury Selivanov in 24450{.interpreted-text role="issue"}.)
  • A new RecursionError{.interpreted-text role="exc"} exception is now raised when maximum recursion depth is reached. (Contributed by Georg Brandl in 19235{.interpreted-text role="issue"}.)

CPython implementation improvements:

  • When the LC_TYPE locale is the POSIX locale (C locale), sys.stdin{.interpreted-text role="py:data"} and sys.stdout{.interpreted-text role="py:data"} now use the surrogateescape error handler, instead of the strict error handler. (Contributed by Victor Stinner in 19977{.interpreted-text role="issue"}.)
  • .pyo files are no longer used and have been replaced by a more flexible scheme that includes the optimization level explicitly in .pyc name. (See PEP 488 overview <whatsnew-pep-488>{.interpreted-text role="ref"}.)
  • Builtin and extension modules are now initialized in a multi-phase process, which is similar to how Python modules are loaded. (See PEP 489 overview <whatsnew-pep-489>{.interpreted-text role="ref"}.)

Significant improvements in the standard library:

  • collections.OrderedDict{.interpreted-text role="class"} is now implemented in C <whatsnew-ordereddict>{.interpreted-text role="ref"}, which makes it 4 to 100 times faster.
  • The ssl{.interpreted-text role="mod"} module gained support for Memory BIO <whatsnew-sslmemorybio>{.interpreted-text role="ref"}, which decouples SSL protocol handling from network IO.
  • The new os.scandir{.interpreted-text role="func"} function provides a better and significantly faster way <whatsnew-pep-471>{.interpreted-text role="ref"} of directory traversal.
  • functools.lru_cache{.interpreted-text role="func"} has been mostly reimplemented in C <whatsnew-lrucache>{.interpreted-text role="ref"}, yielding much better performance.
  • The new subprocess.run{.interpreted-text role="func"} function provides a streamlined way to run subprocesses <whatsnew-subprocess>{.interpreted-text role="ref"}.
  • The traceback{.interpreted-text role="mod"} module has been significantly enhanced <whatsnew-traceback>{.interpreted-text role="ref"} for improved performance and developer convenience.

Security improvements:

  • SSLv3 is now disabled throughout the standard library. It can still be enabled by instantiating a ssl.SSLContext{.interpreted-text role="class"} manually. (See 22638{.interpreted-text role="issue"} for more details; this change was backported to CPython 3.4 and 2.7.)
  • HTTP cookie parsing is now stricter, in order to protect against potential injection attacks. (Contributed by Antoine Pitrou in 22796{.interpreted-text role="issue"}.)

Windows improvements:

  • A new installer for Windows has replaced the old MSI. See using-on-windows{.interpreted-text role="ref"} for more information.
  • Windows builds now use Microsoft Visual C++ 14.0, and extension modules should use the same.

Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.

New Features

PEP 492 - Coroutines with async and await syntax {#whatsnew-pep-492}

492{.interpreted-text role="pep"} greatly improves support for asynchronous programming in Python by adding awaitable objects <awaitable>{.interpreted-text role="term"}, coroutine functions <coroutine function>{.interpreted-text role="term"}, asynchronous iteration <asynchronous iterable>{.interpreted-text role="term"}, and asynchronous context managers <asynchronous context manager>{.interpreted-text role="term"}.

Coroutine functions are declared using the new async def{.interpreted-text role="keyword"} syntax:

>>> async def coro():
...     return 'spam'

Inside a coroutine function, the new await{.interpreted-text role="keyword"} expression can be used to suspend coroutine execution until the result is available. Any object can be awaited, as long as it implements the awaitable{.interpreted-text role="term"} protocol by defining the ~object.__await__{.interpreted-text role="meth"} method.

PEP 492 also adds async for{.interpreted-text role="keyword"} statement for convenient iteration over asynchronous iterables.

An example of a rudimentary HTTP client written using the new syntax:

import asyncio

async def http_get(domain):
    reader, writer = await asyncio.open_connection(domain, 80)

    writer.write(b'\r\n'.join([
        b'GET / HTTP/1.1',
        b'Host: %b' % domain.encode('latin-1'),
        b'Connection: close',
        b'', b''
    ]))

    async for line in reader:
        print('>>>', line)

    writer.close()

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(http_get('example.com'))
finally:
    loop.close()

Similarly to asynchronous iteration, there is a new syntax for asynchronous context managers. The following script:

import asyncio

async def coro(name, lock):
    print('coro {}: waiting for lock'.format(name))
    async with lock:
        print('coro {}: holding the lock'.format(name))
        await asyncio.sleep(1)
        print('coro {}: releasing the lock'.format(name))

loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
    loop.run_until_complete(coros)
finally:
    loop.close()

will output:

coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock

Note that both async for{.interpreted-text role="keyword"} and async with{.interpreted-text role="keyword"} can only be used inside a coroutine function declared with async def{.interpreted-text role="keyword"}.

Coroutine functions are intended to be run inside a compatible event loop, such as the asyncio loop <asyncio-event-loop>{.interpreted-text role="ref"}.

::::: note ::: title Note :::

::: versionchanged 3.5.2 Starting with CPython 3.5.2, __aiter__ can directly return asynchronous iterators <asynchronous iterator>{.interpreted-text role="term"}. Returning an awaitable{.interpreted-text role="term"} object will result in a PendingDeprecationWarning{.interpreted-text role="exc"}.

See more details in the async-iterators{.interpreted-text role="ref"} documentation section. ::: :::::

::: seealso

492{.interpreted-text role="pep"} -- Coroutines with async and await syntax

: PEP written and implemented by Yury Selivanov. :::

PEP 465 - A dedicated infix operator for matrix multiplication {#whatsnew-pep-465}

465{.interpreted-text role="pep"} adds the @ infix operator for matrix multiplication. Currently, no builtin Python types implement the new operator, however, it can be implemented by defining ~object.__matmul__{.interpreted-text role="meth"}, ~object.__rmatmul__{.interpreted-text role="meth"}, and ~object.__imatmul__{.interpreted-text role="meth"} for regular, reflected, and in-place matrix multiplication. The semantics of these methods is similar to that of methods defining other infix arithmetic operators.

Matrix multiplication is a notably common operation in many fields of mathematics, science, engineering, and the addition of @ allows writing cleaner code:

S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

instead of:

S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

NumPy 1.10 has support for the new operator:

>>> import numpy

>>> x = numpy.ones(3)
>>> x
array([ 1., 1., 1.])

>>> m = numpy.eye(3)
>>> m
array([[ 1., 0., 0.],
       [ 0., 1., 0.],
       [ 0., 0., 1.]])

>>> x @ m
array([ 1., 1., 1.])

::: seealso

465{.interpreted-text role="pep"} -- A dedicated infix operator for matrix multiplication

: PEP written by Nathaniel J. Smith; implemented by Benjamin Peterson. :::

PEP 448 - Additional Unpacking Generalizations {#whatsnew-pep-448}

448{.interpreted-text role="pep"} extends the allowed uses of the * iterable unpacking operator and ** dictionary unpacking operator. It is now possible to use an arbitrary number of unpackings in function calls <calls>{.interpreted-text role="ref"}:

>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

>>> def fn(a, b, c, d):
...     print(a, b, c, d)
...

>>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
1 2 3 4

Similarly, tuple, list, set, and dictionary displays allow multiple unpackings (see exprlists{.interpreted-text role="ref"} and dict{.interpreted-text role="ref"}):

>>> *range(4), 4
(0, 1, 2, 3, 4)

>>> [*range(4), 4]
[0, 1, 2, 3, 4]

>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}

>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}

::: seealso

448{.interpreted-text role="pep"} -- Additional Unpacking Generalizations

: PEP written by Joshua Landau; implemented by Neil Girdhar, Thomas Wouters, and Joshua Landau. :::

PEP 461 - percent formatting support for bytes and bytearray {#whatsnew-pep-461}

461{.interpreted-text role="pep"} adds support for the % interpolation operator <bytes-formatting>{.interpreted-text role="ref"} to bytes{.interpreted-text role="class"} and bytearray{.interpreted-text role="class"}.

While interpolation is usually thought of as a string operation, there are cases where interpolation on bytes or bytearrays makes sense, and the work needed to make up for this missing functionality detracts from the overall readability of the code. This issue is particularly important when dealing with wire format protocols, which are often a mixture of binary and ASCII compatible text.

Examples:

>>> b'Hello %b!' % b'World'
b'Hello World!'

>>> b'x=%i y=%f' % (1, 2.5)
b'x=1 y=2.500000'

Unicode is not allowed for %b, but it is accepted by %a (equivalent of repr(obj).encode('ascii', 'backslashreplace')):

>>> b'Hello %b!' % 'World'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'

>>> b'price: %a' % '10€'
b"price: '10\\u20ac'"

Note that %s and %r conversion types, although supported, should only be used in codebases that need compatibility with Python 2.

::: seealso

461{.interpreted-text role="pep"} -- Adding % formatting to bytes and bytearray

: PEP written by Ethan Furman; implemented by Neil Schemenauer and Ethan Furman. :::

PEP 484 - Type Hints {#whatsnew-pep-484}

Function annotation syntax has been a Python feature since version 3.0 (3107{.interpreted-text role="pep"}), however the semantics of annotations has been left undefined.

Experience has shown that the majority of function annotation uses were to provide type hints to function parameters and return values. It became evident that it would be beneficial for Python users, if the standard library included the base definitions and tools for type annotations.

484{.interpreted-text role="pep"} introduces a provisional module <provisional API>{.interpreted-text role="term"} to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.

For example, here is a simple function whose argument and return type are declared in the annotations:

def greeting(name: str) -> str:
    return 'Hello ' + name

While these annotations are available at runtime through the usual ~object.__annotations__{.interpreted-text role="attr"} attribute, no automatic type checking happens at runtime. Instead, it is assumed that a separate off-line type checker (e.g. mypy) will be used for on-demand source code analysis.

The type system supports unions, generic types, and a special type named ~typing.Any{.interpreted-text role="class"} which is consistent with (i.e. assignable to and from) all types.

::: seealso

  • typing{.interpreted-text role="mod"} module documentation

  • 484{.interpreted-text role="pep"} -- Type Hints

    : PEP written by Guido van Rossum, Jukka Lehtosalo, and Łukasz Langa; implemented by Guido van Rossum.

  • 483{.interpreted-text role="pep"} -- The Theory of Type Hints

    : PEP written by Guido van Rossum

:::

PEP 471 - os.scandir() function -- a better and faster directory iterator {#whatsnew-pep-471}

471{.interpreted-text role="pep"} adds a new directory iteration function, os.scandir{.interpreted-text role="func"}, to the standard library. Additionally, os.walk{.interpreted-text role="func"} is now implemented using scandir, which makes it 3 to 5 times faster on POSIX systems and 7 to 20 times faster on Windows systems. This is largely achieved by greatly reducing the number of calls to os.stat{.interpreted-text role="func"} required to walk a directory tree.

Additionally, scandir returns an iterator, as opposed to returning a list of file names, which improves memory efficiency when iterating over very large directories.

The following example shows a simple use of os.scandir{.interpreted-text role="func"} to display all the files (excluding directories) in the given path that don't start with '.'. The entry.is_file() <os.DirEntry.is_file>{.interpreted-text role="meth"} call will generally not make an additional system call:

for entry in os.scandir(path):
    if not entry.name.startswith('.') and entry.is_file():
        print(entry.name)

::: seealso

471{.interpreted-text role="pep"} -- os.scandir() function -- a better and faster directory iterator

: PEP written and implemented by Ben Hoyt with the help of Victor Stinner. :::

PEP 475: Retry system calls failing with EINTR {#whatsnew-pep-475}

An errno.EINTR{.interpreted-text role="py:const"} error code is returned whenever a system call, that is waiting for I/O, is interrupted by a signal. Previously, Python would raise InterruptedError{.interpreted-text role="exc"} in such cases. This meant that, when writing a Python application, the developer had two choices:

  1. Ignore the InterruptedError.
  2. Handle the InterruptedError and attempt to restart the interrupted system call at every call site.

The first option makes an application fail intermittently. The second option adds a large amount of boilerplate that makes the code nearly unreadable. Compare:

print("Hello World")

and:

while True:
    try:
        print("Hello World")
        break
    except InterruptedError:
        continue

475{.interpreted-text role="pep"} implements automatic retry of system calls on EINTR. This removes the burden of dealing with EINTR or InterruptedError{.interpreted-text role="exc"} in user code in most situations and makes Python programs, including the standard library, more robust. Note that the system call is only retried if the signal handler does not raise an exception.

Below is a list of functions which are now retried when interrupted by a signal:

  • open{.interpreted-text role="func"} and io.open{.interpreted-text role="func"};
  • functions of the faulthandler{.interpreted-text role="mod"} module;
  • os{.interpreted-text role="mod"} functions: ~os.fchdir{.interpreted-text role="func"}, ~os.fchmod{.interpreted-text role="func"}, ~os.fchown{.interpreted-text role="func"}, ~os.fdatasync{.interpreted-text role="func"}, ~os.fstat{.interpreted-text role="func"}, ~os.fstatvfs{.interpreted-text role="func"}, ~os.fsync{.interpreted-text role="func"}, ~os.ftruncate{.interpreted-text role="func"}, ~os.mkfifo{.interpreted-text role="func"}, ~os.mknod{.interpreted-text role="func"}, ~os.open{.interpreted-text role="func"}, ~os.posix_fadvise{.interpreted-text role="func"}, ~os.posix_fallocate{.interpreted-text role="func"}, ~os.pread{.interpreted-text role="func"}, ~os.pwrite{.interpreted-text role="func"}, ~os.read{.interpreted-text role="func"}, ~os.readv{.interpreted-text role="func"}, ~os.sendfile{.interpreted-text role="func"}, ~os.wait3{.interpreted-text role="func"}, ~os.wait4{.interpreted-text role="func"}, ~os.wait{.interpreted-text role="func"}, ~os.waitid{.interpreted-text role="func"}, ~os.waitpid{.interpreted-text role="func"}, ~os.write{.interpreted-text role="func"}, ~os.writev{.interpreted-text role="func"};
  • special cases: os.close{.interpreted-text role="func"} and os.dup2{.interpreted-text role="func"} now ignore ~errno.EINTR{.interpreted-text role="py:const"} errors; the syscall is not retried (see the PEP for the rationale);
  • select{.interpreted-text role="mod"} functions: devpoll.poll() <select.devpoll.poll>{.interpreted-text role="func"}, epoll.poll() <select.epoll.poll>{.interpreted-text role="func"}, kqueue.control() <select.kqueue.control>{.interpreted-text role="func"}, poll.poll() <select.poll.poll>{.interpreted-text role="func"}, ~select.select{.interpreted-text role="func"};
  • methods of the ~socket.socket{.interpreted-text role="class"} class: ~socket.socket.accept{.interpreted-text role="meth"}, ~socket.socket.connect{.interpreted-text role="meth"} (except for non-blocking sockets), ~socket.socket.recv{.interpreted-text role="meth"}, ~socket.socket.recvfrom{.interpreted-text role="meth"}, ~socket.socket.recvmsg{.interpreted-text role="meth"}, ~socket.socket.send{.interpreted-text role="meth"}, ~socket.socket.sendall{.interpreted-text role="meth"}, ~socket.socket.sendmsg{.interpreted-text role="meth"}, ~socket.socket.sendto{.interpreted-text role="meth"};
  • signal.sigtimedwait{.interpreted-text role="func"} and signal.sigwaitinfo{.interpreted-text role="func"};
  • time.sleep{.interpreted-text role="func"}.

::: seealso

475{.interpreted-text role="pep"} -- Retry system calls failing with EINTR

: PEP and implementation written by Charles-François Natali and Victor Stinner, with the help of Antoine Pitrou (the French connection). :::

PEP 479: Change StopIteration handling inside generators {#whatsnew-pep-479}

The interaction of generators and StopIteration{.interpreted-text role="exc"} in Python 3.4 and earlier was sometimes surprising, and could conceal obscure bugs. Previously, StopIteration raised accidentally inside a generator function was interpreted as the end of the iteration by the loop construct driving the generator.

479{.interpreted-text role="pep"} changes the behavior of generators: when a StopIteration exception is raised inside a generator, it is replaced with a RuntimeError{.interpreted-text role="exc"} before it exits the generator frame. The main goal of this change is to ease debugging in the situation where an unguarded next{.interpreted-text role="func"} call raises StopIteration and causes the iteration controlled by the generator to terminate silently. This is particularly pernicious in combination with the yield from construct.

This is a backwards incompatible change, so to enable the new behavior, a __future__{.interpreted-text role="term"} import is necessary:

>>> from __future__ import generator_stop

>>> def gen():
...     next(iter([]))
...     yield
...
>>> next(gen())
Traceback (most recent call last):
  File "<stdin>", line 2, in gen
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration

Without a __future__ import, a PendingDeprecationWarning{.interpreted-text role="exc"} will be raised whenever a StopIteration{.interpreted-text role="exc"} exception is raised inside a generator.

::: seealso

479{.interpreted-text role="pep"} -- Change StopIteration handling inside generators

: PEP written by Chris Angelico and Guido van Rossum. Implemented by Chris Angelico, Yury Selivanov and Nick Coghlan. :::

PEP 485: A function for testing approximate equality {#whatsnew-pep-485}

485{.interpreted-text role="pep"} adds the math.isclose{.interpreted-text role="func"} and cmath.isclose{.interpreted-text role="func"} functions which tell whether two values are approximately equal or "close" to each other. Whether or not two values are considered close is determined according to given absolute and relative tolerances. Relative tolerance is the maximum allowed difference between isclose arguments, relative to the larger absolute value:

>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False

It is also possible to compare two values using absolute tolerance, which must be a non-negative value:

>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False

::: seealso

485{.interpreted-text role="pep"} -- A function for testing approximate equality

: PEP written by Christopher Barker; implemented by Chris Barker and Tal Einat. :::

PEP 486: Make the Python Launcher aware of virtual environments {#whatsnew-pep-486}

486{.interpreted-text role="pep"} makes the Windows launcher (see 397{.interpreted-text role="pep"}) aware of an active virtual environment. When the default interpreter would be used and the VIRTUAL_ENV environment variable is set, the interpreter in the virtual environment will be used.

::: seealso

486{.interpreted-text role="pep"} -- Make the Python Launcher aware of virtual environments

: PEP written and implemented by Paul Moore. :::

PEP 488: Elimination of PYO files {#whatsnew-pep-488}

488{.interpreted-text role="pep"} does away with the concept of .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode. To prevent the need to constantly regenerate bytecode files, .pyc files now have an optional opt- tag in their name when the bytecode is optimized. This has the side-effect of no more bytecode file name clashes when running under either -O{.interpreted-text role="option"} or -OO{.interpreted-text role="option"}. Consequently, bytecode files generated from -O{.interpreted-text role="option"}, and -OO{.interpreted-text role="option"} may now exist simultaneously. importlib.util.cache_from_source{.interpreted-text role="func"} has an updated API to help with this change.

::: seealso

488{.interpreted-text role="pep"} -- Elimination of PYO files

: PEP written and implemented by Brett Cannon. :::

PEP 489: Multi-phase extension module initialization {#whatsnew-pep-489}

489{.interpreted-text role="pep"} updates extension module initialization to take advantage of the two step module loading mechanism introduced by 451{.interpreted-text role="pep"} in Python 3.4.

This change brings the import semantics of extension modules that opt-in to using the new mechanism much closer to those of Python source and bytecode modules, including the ability to use any valid identifier as a module name, rather than being restricted to ASCII.

::: seealso

489{.interpreted-text role="pep"} -- Multi-phase extension module initialization

: PEP written by Petr Viktorin, Stefan Behnel, and Nick Coghlan; implemented by Petr Viktorin. :::

Other Language Changes

Some smaller changes made to the core Python language are:

  • Added the "namereplace" error handlers. The "backslashreplace" error handlers now work with decoding and translating. (Contributed by Serhiy Storchaka in 19676{.interpreted-text role="issue"} and 22286{.interpreted-text role="issue"}.)
  • The -b{.interpreted-text role="option"} option now affects comparisons of bytes{.interpreted-text role="class"} with int{.interpreted-text role="class"}. (Contributed by Serhiy Storchaka in 23681{.interpreted-text role="issue"}.)
  • New Kazakh kz1048 and Tajik koi8_t codecs <standard-encodings>{.interpreted-text role="ref"}. (Contributed by Serhiy Storchaka in 22682{.interpreted-text role="issue"} and 22681{.interpreted-text role="issue"}.)
  • Property docstrings are now writable. This is especially useful for collections.namedtuple{.interpreted-text role="func"} docstrings. (Contributed by Berker Peksag in 24064{.interpreted-text role="issue"}.)
  • Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in 17636{.interpreted-text role="issue"}.)

New Modules

typing

The new typing{.interpreted-text role="mod"} provisional <provisional API>{.interpreted-text role="term"} module provides standard definitions and tools for function type annotations. See Type Hints <whatsnew-pep-484>{.interpreted-text role="ref"} for more information.

zipapp {#whatsnew-zipapp}

The new zipapp{.interpreted-text role="mod"} module (specified in 441{.interpreted-text role="pep"}) provides an API and command line tool for creating executable Python Zip Applications, which were introduced in Python 2.6 in 1739468{.interpreted-text role="issue"}, but which were not well publicized, either at the time or since.

With the new module, bundling your application is as simple as putting all the files, including a __main__.py file, into a directory myapp and running:

$ python -m zipapp myapp
$ python myapp.pyz

The module implementation has been contributed by Paul Moore in 23491{.interpreted-text role="issue"}.

::: seealso 441{.interpreted-text role="pep"} -- Improving Python ZIP Application Support :::

Improved Modules

argparse

The ~argparse.ArgumentParser{.interpreted-text role="class"} class now allows disabling abbreviated usage <prefix-matching>{.interpreted-text role="ref"} of long options by setting allow_abbrev{.interpreted-text role="ref"} to False. (Contributed by Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson in 14910{.interpreted-text role="issue"}.)

asyncio

Since the asyncio{.interpreted-text role="mod"} module is provisional <provisional API>{.interpreted-text role="term"}, all changes introduced in Python 3.5 have also been backported to Python 3.4.x.

Notable changes in the asyncio{.interpreted-text role="mod"} module since Python 3.4.0:

  • New debugging APIs: loop.set_debug() <asyncio.loop.set_debug>{.interpreted-text role="meth"} and loop.get_debug() <asyncio.loop.get_debug>{.interpreted-text role="meth"} methods. (Contributed by Victor Stinner.)
  • The proactor event loop now supports SSL. (Contributed by Antoine Pitrou and Victor Stinner in 22560{.interpreted-text role="issue"}.)
  • A new loop.is_closed() <asyncio.loop.is_closed>{.interpreted-text role="meth"} method to check if the event loop is closed. (Contributed by Victor Stinner in 21326{.interpreted-text role="issue"}.)
  • A new loop.create_task() <asyncio.loop.create_task>{.interpreted-text role="meth"} to conveniently create and schedule a new ~asyncio.Task{.interpreted-text role="class"} for a coroutine. The create_task method is also used by all asyncio functions that wrap coroutines into tasks, such as asyncio.wait{.interpreted-text role="func"}, asyncio.gather{.interpreted-text role="func"}, etc. (Contributed by Victor Stinner.)
  • A new transport.get_write_buffer_limits() <asyncio.WriteTransport.get_write_buffer_limits>{.interpreted-text role="meth"} method to inquire for high- and low- water limits of the flow control. (Contributed by Victor Stinner.)
  • The !async{.interpreted-text role="func"} function is deprecated in favor of ~asyncio.ensure_future{.interpreted-text role="func"}. (Contributed by Yury Selivanov.)
  • New loop.set_task_factory() <asyncio.loop.set_task_factory>{.interpreted-text role="meth"} and loop.get_task_factory() <asyncio.loop.get_task_factory>{.interpreted-text role="meth"} methods to customize the task factory that loop.create_task() <asyncio.loop.create_task>{.interpreted-text role="meth"} method uses. (Contributed by Yury Selivanov.)
  • New Queue.join() <asyncio.Queue.join>{.interpreted-text role="meth"} and Queue.task_done() <asyncio.Queue.task_done>{.interpreted-text role="meth"} queue methods. (Contributed by Victor Stinner.)
  • The JoinableQueue class was removed, in favor of the asyncio.Queue{.interpreted-text role="class"} class. (Contributed by Victor Stinner.)

Updates in 3.5.1:

  • The ~asyncio.ensure_future{.interpreted-text role="func"} function and all functions that use it, such as loop.run_until_complete() <asyncio.loop.run_until_complete>{.interpreted-text role="meth"}, now accept all kinds of awaitable objects <awaitable>{.interpreted-text role="term"}. (Contributed by Yury Selivanov.)
  • New ~asyncio.run_coroutine_threadsafe{.interpreted-text role="func"} function to submit coroutines to event loops from other threads. (Contributed by Vincent Michel.)
  • New Transport.is_closing() <asyncio.BaseTransport.is_closing>{.interpreted-text role="meth"} method to check if the transport is closing or closed. (Contributed by Yury Selivanov.)
  • The loop.create_server() <asyncio.loop.create_server>{.interpreted-text role="meth"} method can now accept a list of hosts. (Contributed by Yann Sionneau.)

Updates in 3.5.2:

  • New loop.create_future() <asyncio.loop.create_future>{.interpreted-text role="meth"} method to create Future objects. This allows alternative event loop implementations, such as uvloop, to provide a faster asyncio.Future{.interpreted-text role="class"} implementation. (Contributed by Yury Selivanov.)
  • New loop.get_exception_handler() <asyncio.loop.get_exception_handler>{.interpreted-text role="meth"} method to get the current exception handler. (Contributed by Yury Selivanov.)
  • New StreamReader.readuntil() <asyncio.StreamReader.readuntil>{.interpreted-text role="meth"} method to read data from the stream until a separator bytes sequence appears. (Contributed by Mark Korenberg.)
  • The loop.create_connection() <asyncio.loop.create_connection>{.interpreted-text role="meth"} and loop.create_server() <asyncio.loop.create_server>{.interpreted-text role="meth"} methods are optimized to avoid calling the system getaddrinfo function if the address is already resolved. (Contributed by A. Jesse Jiryu Davis.)
  • The loop.sock_connect(sock, address) <asyncio.loop.sock_connect>{.interpreted-text role="meth"} no longer requires the address to be resolved prior to the call. (Contributed by A. Jesse Jiryu Davis.)

bz2

The BZ2Decompressor.decompress <bz2.BZ2Decompressor.decompress>{.interpreted-text role="meth"} method now accepts an optional max_length argument to limit the maximum size of decompressed data. (Contributed by Nikolaus Rath in 15955{.interpreted-text role="issue"}.)

cgi

The !FieldStorage{.interpreted-text role="class"} class now supports the context manager{.interpreted-text role="term"} protocol. (Contributed by Berker Peksag in 20289{.interpreted-text role="issue"}.)

cmath

A new function ~cmath.isclose{.interpreted-text role="func"} provides a way to test for approximate equality. (Contributed by Chris Barker and Tal Einat in 24270{.interpreted-text role="issue"}.)

code

The InteractiveInterpreter.showtraceback() <code.InteractiveInterpreter.showtraceback>{.interpreted-text role="func"} method now prints the full chained traceback, just like the interactive interpreter. (Contributed by Claudiu Popa in 17442{.interpreted-text role="issue"}.)

collections

::: {#whatsnew-ordereddict} The ~collections.OrderedDict{.interpreted-text role="class"} class is now implemented in C, which makes it 4 to 100 times faster. (Contributed by Eric Snow in 16991{.interpreted-text role="issue"}.) :::

!OrderedDict.items{.interpreted-text role="meth"}, !OrderedDict.keys{.interpreted-text role="meth"}, and !OrderedDict.values{.interpreted-text role="meth"} views now support reversed{.interpreted-text role="func"} iteration. (Contributed by Serhiy Storchaka in 19505{.interpreted-text role="issue"}.)

The ~collections.deque{.interpreted-text role="class"} class now defines ~collections.deque.index{.interpreted-text role="meth"}, ~collections.deque.insert{.interpreted-text role="meth"}, and ~collections.deque.copy{.interpreted-text role="meth"}, and supports the + and * operators. This allows deques to be recognized as a ~collections.abc.MutableSequence{.interpreted-text role="class"} and improves their substitutability for lists. (Contributed by Raymond Hettinger in 23704{.interpreted-text role="issue"}.)

Docstrings produced by ~collections.namedtuple{.interpreted-text role="func"} can now be updated:

Point = namedtuple('Point', ['x', 'y'])
Point.__doc__ += ': Cartesian coordinate'
Point.x.__doc__ = 'abscissa'
Point.y.__doc__ = 'ordinate'

(Contributed by Berker Peksag in 24064{.interpreted-text role="issue"}.)

The ~collections.UserString{.interpreted-text role="class"} class now implements the ~object.__getnewargs__{.interpreted-text role="meth"}, ~object.__rmod__{.interpreted-text role="meth"}, ~str.casefold{.interpreted-text role="meth"}, ~str.format_map{.interpreted-text role="meth"}, ~str.isprintable{.interpreted-text role="meth"}, and ~str.maketrans{.interpreted-text role="meth"} methods to match the corresponding methods of str{.interpreted-text role="class"}. (Contributed by Joe Jevnik in 22189{.interpreted-text role="issue"}.)

collections.abc

The !Sequence.index{.interpreted-text role="meth"} method now accepts start and stop arguments to match the corresponding methods of tuple{.interpreted-text role="class"}, list{.interpreted-text role="class"}, etc. (Contributed by Devin Jeanpierre in 23086{.interpreted-text role="issue"}.)

A new ~collections.abc.Generator{.interpreted-text role="class"} abstract base class. (Contributed by Stefan Behnel in 24018{.interpreted-text role="issue"}.)

New ~collections.abc.Awaitable{.interpreted-text role="class"}, ~collections.abc.Coroutine{.interpreted-text role="class"}, ~collections.abc.AsyncIterator{.interpreted-text role="class"}, and ~collections.abc.AsyncIterable{.interpreted-text role="class"} abstract base classes. (Contributed by Yury Selivanov in 24184{.interpreted-text role="issue"}.)

For earlier Python versions, a backport of the new ABCs is available in an external PyPI package <backports_abc>{.interpreted-text role="pypi"}.

compileall

A new compileall{.interpreted-text role="mod"} option, -j {N}{.interpreted-text role="samp"}, allows running N workers simultaneously to perform parallel bytecode compilation. The ~compileall.compile_dir{.interpreted-text role="func"} function has a corresponding workers parameter. (Contributed by Claudiu Popa in 16104{.interpreted-text role="issue"}.)

Another new option, -r, allows controlling the maximum recursion level for subdirectories. (Contributed by Claudiu Popa in 19628{.interpreted-text role="issue"}.)

The -q command line option can now be specified more than once, in which case all output, including errors, will be suppressed. The corresponding quiet parameter in ~compileall.compile_dir{.interpreted-text role="func"}, ~compileall.compile_file{.interpreted-text role="func"}, and ~compileall.compile_path{.interpreted-text role="func"} can now accept an integer value indicating the level of output suppression. (Contributed by Thomas Kluyver in 21338{.interpreted-text role="issue"}.)

concurrent.futures

The Executor.map() <concurrent.futures.Executor.map>{.interpreted-text role="meth"} method now accepts a chunksize argument to allow batching of tasks to improve performance when ~concurrent.futures.ProcessPoolExecutor{.interpreted-text role="meth"} is used. (Contributed by Dan O'Reilly in 11271{.interpreted-text role="issue"}.)

The number of workers in the ~concurrent.futures.ThreadPoolExecutor{.interpreted-text role="class"} constructor is optional now. The default value is 5 times the number of CPUs. (Contributed by Claudiu Popa in 21527{.interpreted-text role="issue"}.)

configparser

configparser{.interpreted-text role="mod"} now provides a way to customize the conversion of values by specifying a dictionary of converters in the ~configparser.ConfigParser{.interpreted-text role="class"} constructor, or by defining them as methods in ConfigParser subclasses. Converters defined in a parser instance are inherited by its section proxies.

Example:

>>> import configparser
>>> conv = {}
>>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
>>> cfg = configparser.ConfigParser(converters=conv)
>>> cfg.read_string("""
... [s]
... list = a b c d e f g
... """)
>>> cfg.get('s', 'list')
'a b c d e f g'
>>> cfg.getlist('s', 'list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> section = cfg['s']
>>> section.getlist('list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']

(Contributed by Łukasz Langa in 18159{.interpreted-text role="issue"}.)

contextlib

The new ~contextlib.redirect_stderr{.interpreted-text role="func"} context manager{.interpreted-text role="term"} (similar to ~contextlib.redirect_stdout{.interpreted-text role="func"}) makes it easier for utility scripts to handle inflexible APIs that write their output to sys.stderr{.interpreted-text role="data"} and don't provide any options to redirect it:

>>> import contextlib, io, logging
>>> f = io.StringIO()
>>> with contextlib.redirect_stderr(f):
...     logging.warning('warning')
...
>>> f.getvalue()
'WARNING:root:warning\n'

(Contributed by Berker Peksag in 22389{.interpreted-text role="issue"}.)

csv

The ~csv.csvwriter.writerow{.interpreted-text role="meth"} method now supports arbitrary iterables, not just sequences. (Contributed by Serhiy Storchaka in 23171{.interpreted-text role="issue"}.)

curses

The new ~curses.update_lines_cols{.interpreted-text role="func"} function updates the ~curses.LINES{.interpreted-text role="data"} and ~curses.COLS{.interpreted-text role="data"} module variables. This is useful for detecting manual screen resizing. (Contributed by Arnon Yaari in 4254{.interpreted-text role="issue"}.)

dbm

dumb.open <dbm.dumb.open>{.interpreted-text role="func"} always creates a new database when the flag has the value "n". (Contributed by Claudiu Popa in 18039{.interpreted-text role="issue"}.)

difflib

The charset of HTML documents generated by HtmlDiff.make_file() <difflib.HtmlDiff.make_file>{.interpreted-text role="meth"} can now be customized by using a new charset keyword-only argument. The default charset of HTML document changed from "ISO-8859-1" to "utf-8". (Contributed by Berker Peksag in 2052{.interpreted-text role="issue"}.)

The ~difflib.diff_bytes{.interpreted-text role="func"} function can now compare lists of byte strings. This fixes a regression from Python 2. (Contributed by Terry J. Reedy and Greg Ward in 17445{.interpreted-text role="issue"}.)

distutils

Both the build and build_ext commands now accept a -j option to enable parallel building of extension modules. (Contributed by Antoine Pitrou in 5309{.interpreted-text role="issue"}.)

The distutils module now supports xz compression, and can be enabled by passing xztar as an argument to bdist --format. (Contributed by Serhiy Storchaka in 16314{.interpreted-text role="issue"}.)

doctest

The ~doctest.DocTestSuite{.interpreted-text role="func"} function returns an empty unittest.TestSuite{.interpreted-text role="class"} if module contains no docstrings, instead of raising ValueError{.interpreted-text role="exc"}. (Contributed by Glenn Jones in 15916{.interpreted-text role="issue"}.)

email

A new policy option Policy.mangle_from_ <email.policy.Policy.mangle_from_>{.interpreted-text role="attr"} controls whether or not lines that start with "From " in email bodies are prefixed with a ">" character by generators. The default is True for ~email.policy.compat32{.interpreted-text role="attr"} and False for all other policies. (Contributed by Milan Oberkirch in 20098{.interpreted-text role="issue"}.)

A new Message.get_content_disposition() <email.message.Message.get_content_disposition>{.interpreted-text role="meth"} method provides easy access to a canonical value for the Content-Disposition{.interpreted-text role="mailheader"} header. (Contributed by Abhilash Raj in 21083{.interpreted-text role="issue"}.)

A new policy option EmailPolicy.utf8 <email.policy.EmailPolicy.utf8>{.interpreted-text role="attr"} can be set to True to encode email headers using the UTF-8 charset instead of using encoded words. This allows Messages to be formatted according to 6532{.interpreted-text role="rfc"} and used with an SMTP server that supports the 6531{.interpreted-text role="rfc"} SMTPUTF8 extension. (Contributed by R. David Murray in 24211{.interpreted-text role="issue"}.)

The mime.text.MIMEText <email.mime.text.MIMEText>{.interpreted-text role="class"} constructor now accepts a charset.Charset <email.charset.Charset>{.interpreted-text role="class"} instance. (Contributed by Claude Paroz and Berker Peksag in 16324{.interpreted-text role="issue"}.)

enum

The ~enum.Enum{.interpreted-text role="class"} callable has a new parameter start to specify the initial number of enum values if only names are provided:

>>> Animal = enum.Enum('Animal', 'cat dog', start=10)
>>> Animal.cat
<Animal.cat: 10>
>>> Animal.dog
<Animal.dog: 11>

(Contributed by Ethan Furman in 21706{.interpreted-text role="issue"}.)

faulthandler

The ~faulthandler.enable{.interpreted-text role="func"}, ~faulthandler.register{.interpreted-text role="func"}, ~faulthandler.dump_traceback{.interpreted-text role="func"} and ~faulthandler.dump_traceback_later{.interpreted-text role="func"} functions now accept file descriptors in addition to file-like objects. (Contributed by Wei Wu in 23566{.interpreted-text role="issue"}.)

functools

::: {#whatsnew-lrucache} Most of the ~functools.lru_cache{.interpreted-text role="func"} machinery is now implemented in C, making it significantly faster. (Contributed by Matt Joiner, Alexey Kachayev, and Serhiy Storchaka in 14373{.interpreted-text role="issue"}.) :::

glob

The ~glob.iglob{.interpreted-text role="func"} and ~glob.glob{.interpreted-text role="func"} functions now support recursive search in subdirectories, using the "**" pattern. (Contributed by Serhiy Storchaka in 13968{.interpreted-text role="issue"}.)

gzip

The mode argument of the ~gzip.GzipFile{.interpreted-text role="class"} constructor now accepts "x" to request exclusive creation. (Contributed by Tim Heaney in 19222{.interpreted-text role="issue"}.)

heapq

Element comparison in ~heapq.merge{.interpreted-text role="func"} can now be customized by passing a key function{.interpreted-text role="term"} in a new optional key keyword argument, and a new optional reverse keyword argument can be used to reverse element comparison:

>>> import heapq
>>> a = ['9', '777', '55555']
>>> b = ['88', '6666']
>>> list(heapq.merge(a, b, key=len))
['9', '88', '777', '6666', '55555']
>>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
['55555', '6666', '777', '88', '9']

(Contributed by Raymond Hettinger in 13742{.interpreted-text role="issue"}.)

http

A new HTTPStatus <http.HTTPStatus>{.interpreted-text role="class"} enum that defines a set of HTTP status codes, reason phrases and long descriptions written in English. (Contributed by Demian Brecht in 21793{.interpreted-text role="issue"}.)

http.client

HTTPConnection.getresponse() <http.client.HTTPConnection.getresponse>{.interpreted-text role="meth"} now raises a ~http.client.RemoteDisconnected{.interpreted-text role="exc"} exception when a remote server connection is closed unexpectedly. Additionally, if a ConnectionError{.interpreted-text role="exc"} (of which RemoteDisconnected is a subclass) is raised, the client socket is now closed automatically, and will reconnect on the next request:

import http.client
conn = http.client.HTTPConnection('www.python.org')
for retries in range(3):
    try:
        conn.request('GET', '/')
        resp = conn.getresponse()
    except http.client.RemoteDisconnected:
        pass

(Contributed by Martin Panter in 3566{.interpreted-text role="issue"}.)

idlelib and IDLE

Since idlelib implements the IDLE shell and editor and is not intended for import by other programs, it gets improvements with every release. See Lib/idlelib/NEWS.txt{.interpreted-text role="file"} for a cumulative list of changes since 3.4.0, as well as changes made in future 3.5.x releases. This file is also available from the IDLE Help --> About IDLE{.interpreted-text role="menuselection"} dialog.

imaplib

The ~imaplib.IMAP4{.interpreted-text role="class"} class now supports the context manager{.interpreted-text role="term"} protocol. When used in a with{.interpreted-text role="keyword"} statement, the IMAP4 LOGOUT command will be called automatically at the end of the block. (Contributed by Tarek Ziadé and Serhiy Storchaka in 4972{.interpreted-text role="issue"}.)

The imaplib{.interpreted-text role="mod"} module now supports 5161{.interpreted-text role="rfc"} (ENABLE Extension) and 6855{.interpreted-text role="rfc"} (UTF-8 Support) via the IMAP4.enable() <imaplib.IMAP4.enable>{.interpreted-text role="meth"} method. A new IMAP4.utf8_enabled <imaplib.IMAP4.utf8_enabled>{.interpreted-text role="attr"} attribute tracks whether or not 6855{.interpreted-text role="rfc"} support is enabled. (Contributed by Milan Oberkirch, R. David Murray, and Maciej Szulik in 21800{.interpreted-text role="issue"}.)

The imaplib{.interpreted-text role="mod"} module now automatically encodes non-ASCII string usernames and passwords using UTF-8, as recommended by the RFCs. (Contributed by Milan Oberkirch in 21800{.interpreted-text role="issue"}.)

imghdr

The !what{.interpreted-text role="func"} function now recognizes the OpenEXR format (contributed by Martin Vignali and Claudiu Popa in 20295{.interpreted-text role="issue"}), and the WebP format (contributed by Fabrice Aneche and Claudiu Popa in 20197{.interpreted-text role="issue"}.)

importlib

The util.LazyLoader <importlib.util.LazyLoader>{.interpreted-text role="class"} class allows for lazy loading of modules in applications where startup time is important. (Contributed by Brett Cannon in 17621{.interpreted-text role="issue"}.)

The abc.InspectLoader.source_to_code() <importlib.abc.InspectLoader.source_to_code>{.interpreted-text role="func"} method is now a static method. This makes it easier to initialize a module object with code compiled from a string by running exec(code, module.__dict__). (Contributed by Brett Cannon in 21156{.interpreted-text role="issue"}.)

The new util.module_from_spec() <importlib.util.module_from_spec>{.interpreted-text role="func"} function is now the preferred way to create a new module. As opposed to creating a types.ModuleType{.interpreted-text role="class"} instance directly, this new function will set the various import-controlled attributes based on the passed-in spec object. (Contributed by Brett Cannon in 20383{.interpreted-text role="issue"}.)

inspect

Both the ~inspect.Signature{.interpreted-text role="class"} and ~inspect.Parameter{.interpreted-text role="class"} classes are now picklable and hashable. (Contributed by Yury Selivanov in 20726{.interpreted-text role="issue"} and 20334{.interpreted-text role="issue"}.)

A new BoundArguments.apply_defaults() <inspect.BoundArguments.apply_defaults>{.interpreted-text role="meth"} method provides a way to set default values for missing arguments:

>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

(Contributed by Yury Selivanov in 24190{.interpreted-text role="issue"}.)

A new class method Signature.from_callable() <inspect.Signature.from_callable>{.interpreted-text role="meth"} makes subclassing of ~inspect.Signature{.interpreted-text role="class"} easier. (Contributed by Yury Selivanov and Eric Snow in 17373{.interpreted-text role="issue"}.)

The ~inspect.signature{.interpreted-text role="func"} function now accepts a follow_wrapped optional keyword argument, which, when set to False, disables automatic following of __wrapped__ links. (Contributed by Yury Selivanov in 20691{.interpreted-text role="issue"}.)

A set of new functions to inspect coroutine functions <coroutine function>{.interpreted-text role="term"} and coroutine objects <coroutine>{.interpreted-text role="term"} has been added: ~inspect.iscoroutine{.interpreted-text role="func"}, ~inspect.iscoroutinefunction{.interpreted-text role="func"}, ~inspect.isawaitable{.interpreted-text role="func"}, ~inspect.getcoroutinelocals{.interpreted-text role="func"}, and ~inspect.getcoroutinestate{.interpreted-text role="func"}. (Contributed by Yury Selivanov in 24017{.interpreted-text role="issue"} and 24400{.interpreted-text role="issue"}.)

The ~inspect.stack{.interpreted-text role="func"}, ~inspect.trace{.interpreted-text role="func"}, ~inspect.getouterframes{.interpreted-text role="func"}, and ~inspect.getinnerframes{.interpreted-text role="func"} functions now return a list of named tuples. (Contributed by Daniel Shahaf in 16808{.interpreted-text role="issue"}.)

io

A new BufferedIOBase.readinto1() <io.BufferedIOBase.readinto1>{.interpreted-text role="meth"} method, that uses at most one call to the underlying raw stream's RawIOBase.read() <io.RawIOBase.read>{.interpreted-text role="meth"} or RawIOBase.readinto() <io.RawIOBase.readinto>{.interpreted-text role="meth"} methods. (Contributed by Nikolaus Rath in 20578{.interpreted-text role="issue"}.)

ipaddress

Both the ~ipaddress.IPv4Network{.interpreted-text role="class"} and ~ipaddress.IPv6Network{.interpreted-text role="class"} classes now accept an (address, netmask) tuple argument, so as to easily construct network objects from existing addresses:

>>> import ipaddress
>>> ipaddress.IPv4Network(('127.0.0.0', 8))
IPv4Network('127.0.0.0/8')
>>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
IPv4Network('127.0.0.0/8')

(Contributed by Peter Moody and Antoine Pitrou in 16531{.interpreted-text role="issue"}.)

A new ~ipaddress.IPv4Address.reverse_pointer{.interpreted-text role="attr"} attribute for the ~ipaddress.IPv4Address{.interpreted-text role="class"} and ~ipaddress.IPv6Address{.interpreted-text role="class"} classes returns the name of the reverse DNS PTR record:

>>> import ipaddress
>>> addr = ipaddress.IPv4Address('127.0.0.1')
>>> addr.reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> addr6 = ipaddress.IPv6Address('::1')
>>> addr6.reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'

(Contributed by Leon Weber in 20480{.interpreted-text role="issue"}.)

json

The json.tool{.interpreted-text role="mod"} command line interface now preserves the order of keys in JSON objects passed in input. The new --sort-keys option can be used to sort the keys alphabetically. (Contributed by Berker Peksag in 21650{.interpreted-text role="issue"}.)

JSON decoder now raises ~json.JSONDecodeError{.interpreted-text role="exc"} instead of ValueError{.interpreted-text role="exc"} to provide better context information about the error. (Contributed by Serhiy Storchaka in 19361{.interpreted-text role="issue"}.)

linecache

A new ~linecache.lazycache{.interpreted-text role="func"} function can be used to capture information about a non-file-based module to permit getting its lines later via ~linecache.getline{.interpreted-text role="func"}. This avoids doing I/O until a line is actually needed, without having to carry the module globals around indefinitely. (Contributed by Robert Collins in 17911{.interpreted-text role="issue"}.)

locale

A new ~locale.delocalize{.interpreted-text role="func"} function can be used to convert a string into a normalized number string, taking the LC_NUMERIC settings into account:

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
'de_DE.UTF-8'
>>> locale.delocalize('1.234,56')
'1234.56'
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.delocalize('1,234.56')
'1234.56'

(Contributed by Cédric Krier in 13918{.interpreted-text role="issue"}.)

logging

All logging methods (~logging.Logger{.interpreted-text role="class"} ~logging.Logger.log{.interpreted-text role="meth"}, ~logging.Logger.exception{.interpreted-text role="meth"}, ~logging.Logger.critical{.interpreted-text role="meth"}, ~logging.Logger.debug{.interpreted-text role="meth"}, etc.), now accept exception instances as an exc_info argument, in addition to boolean values and exception tuples:

>>> import logging
>>> try:
...     1/0
... except ZeroDivisionError as ex:
...     logging.error('exception', exc_info=ex)
ERROR:root:exception

(Contributed by Yury Selivanov in 20537{.interpreted-text role="issue"}.)

The handlers.HTTPHandler <logging.handlers.HTTPHandler>{.interpreted-text role="class"} class now accepts an optional ssl.SSLContext{.interpreted-text role="class"} instance to configure SSL settings used in an HTTP connection. (Contributed by Alex Gaynor in 22788{.interpreted-text role="issue"}.)

The handlers.QueueListener <logging.handlers.QueueListener>{.interpreted-text role="class"} class now takes a respect_handler_level keyword argument which, if set to True, will pass messages to handlers taking handler levels into account. (Contributed by Vinay Sajip.)

lzma

The LZMADecompressor.decompress() <lzma.LZMADecompressor.decompress>{.interpreted-text role="meth"} method now accepts an optional max_length argument to limit the maximum size of decompressed data. (Contributed by Martin Panter in 15955{.interpreted-text role="issue"}.)

math

Two new constants have been added to the math{.interpreted-text role="mod"} module: ~math.inf{.interpreted-text role="data"} and ~math.nan{.interpreted-text role="data"}. (Contributed by Mark Dickinson in 23185{.interpreted-text role="issue"}.)

A new function ~math.isclose{.interpreted-text role="func"} provides a way to test for approximate equality. (Contributed by Chris Barker and Tal Einat in 24270{.interpreted-text role="issue"}.)

A new ~math.gcd{.interpreted-text role="func"} function has been added. The !fractions.gcd{.interpreted-text role="func"} function is now deprecated. (Contributed by Mark Dickinson and Serhiy Storchaka in 22486{.interpreted-text role="issue"}.)

multiprocessing

sharedctypes.synchronized() <multiprocessing.sharedctypes.synchronized>{.interpreted-text role="func"} objects now support the context manager{.interpreted-text role="term"} protocol. (Contributed by Charles-François Natali in 21565{.interpreted-text role="issue"}.)

operator

~operator.attrgetter{.interpreted-text role="func"}, ~operator.itemgetter{.interpreted-text role="func"}, and ~operator.methodcaller{.interpreted-text role="func"} objects now support pickling. (Contributed by Josh Rosenberg and Serhiy Storchaka in 22955{.interpreted-text role="issue"}.)

New ~operator.matmul{.interpreted-text role="func"} and ~operator.imatmul{.interpreted-text role="func"} functions to perform matrix multiplication. (Contributed by Benjamin Peterson in 21176{.interpreted-text role="issue"}.)

os

The new ~os.scandir{.interpreted-text role="func"} function returning an iterator of ~os.DirEntry{.interpreted-text role="class"} objects has been added. If possible, ~os.scandir{.interpreted-text role="func"} extracts file attributes while scanning a directory, removing the need to perform subsequent system calls to determine file type or attributes, which may significantly improve performance. (Contributed by Ben Hoyt with the help of Victor Stinner in 22524{.interpreted-text role="issue"}.)

On Windows, a new stat_result.st_file_attributes <os.stat_result.st_file_attributes>{.interpreted-text role="attr"} attribute is now available. It corresponds to the dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). (Contributed by Ben Hoyt in 21719{.interpreted-text role="issue"}.)

The ~os.urandom{.interpreted-text role="func"} function now uses the getrandom() syscall on Linux 3.17 or newer, and getentropy() on OpenBSD 5.6 and newer, removing the need to use /dev/urandom and avoiding failures due to potential file descriptor exhaustion. (Contributed by Victor Stinner in 22181{.interpreted-text role="issue"}.)

New ~os.get_blocking{.interpreted-text role="func"} and ~os.set_blocking{.interpreted-text role="func"} functions allow getting and setting a file descriptor's blocking mode (~os.O_NONBLOCK{.interpreted-text role="const"}.) (Contributed by Victor Stinner in 22054{.interpreted-text role="issue"}.)

The ~os.truncate{.interpreted-text role="func"} and ~os.ftruncate{.interpreted-text role="func"} functions are now supported on Windows. (Contributed by Steve Dower in 23668{.interpreted-text role="issue"}.)

There is a new os.path.commonpath{.interpreted-text role="func"} function returning the longest common sub-path of each passed pathname. Unlike the os.path.commonprefix{.interpreted-text role="func"} function, it always returns a valid path:

>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'

(Contributed by Rafik Draoui and Serhiy Storchaka in 10395{.interpreted-text role="issue"}.)

pathlib

The new Path.samefile() <pathlib.Path.samefile>{.interpreted-text role="meth"} method can be used to check whether the path points to the same file as another path, which can be either another ~pathlib.Path{.interpreted-text role="class"} object, or a string:

>>> import pathlib
>>> p1 = pathlib.Path('/etc/hosts')
>>> p2 = pathlib.Path('/etc/../etc/hosts')
>>> p1.samefile(p2)
True

(Contributed by Vajrasky Kok and Antoine Pitrou in 19775{.interpreted-text role="issue"}.)

The Path.mkdir() <pathlib.Path.mkdir>{.interpreted-text role="meth"} method now accepts a new optional exist_ok argument to match mkdir -p and os.makedirs{.interpreted-text role="func"} functionality. (Contributed by Berker Peksag in 21539{.interpreted-text role="issue"}.)

There is a new Path.expanduser() <pathlib.Path.expanduser>{.interpreted-text role="meth"} method to expand ~ and ~user prefixes. (Contributed by Serhiy Storchaka and Claudiu Popa in 19776{.interpreted-text role="issue"}.)

A new Path.home() <pathlib.Path.home>{.interpreted-text role="meth"} class method can be used to get a ~pathlib.Path{.interpreted-text role="class"} instance representing the user's home directory. (Contributed by Victor Salgado and Mayank Tripathi in 19777{.interpreted-text role="issue"}.)

New Path.write_text() <pathlib.Path.write_text>{.interpreted-text role="meth"}, Path.read_text() <pathlib.Path.read_text>{.interpreted-text role="meth"}, Path.write_bytes() <pathlib.Path.write_bytes>{.interpreted-text role="meth"}, Path.read_bytes() <pathlib.Path.read_bytes>{.interpreted-text role="meth"} methods to simplify read/write operations on files.

The following code snippet will create or rewrite existing file ~/spam42:

>>> import pathlib
>>> p = pathlib.Path('~/spam42')
>>> p.expanduser().write_text('ham')
3

(Contributed by Christopher Welborn in 20218{.interpreted-text role="issue"}.)

pickle

Nested objects, such as unbound methods or nested classes, can now be pickled using pickle protocols <pickle-protocols>{.interpreted-text role="ref"} older than protocol version 4. Protocol version 4 already supports these cases. (Contributed by Serhiy Storchaka in 23611{.interpreted-text role="issue"}.)

poplib

A new POP3.utf8() <poplib.POP3.utf8>{.interpreted-text role="meth"} command enables 6856{.interpreted-text role="rfc"} (Internationalized Email) support, if a POP server supports it. (Contributed by Milan OberKirch in 21804{.interpreted-text role="issue"}.)

re

References and conditional references to groups with fixed length are now allowed in lookbehind assertions:

>>> import re
>>> pat = re.compile(r'(a|b).(?<=\1)c')
>>> pat.match('aac')
<_sre.SRE_Match object; span=(0, 3), match='aac'>
>>> pat.match('bbc')
<_sre.SRE_Match object; span=(0, 3), match='bbc'>

(Contributed by Serhiy Storchaka in 9179{.interpreted-text role="issue"}.)

The number of capturing groups in regular expressions is no longer limited to 100. (Contributed by Serhiy Storchaka in 22437{.interpreted-text role="issue"}.)

The ~re.sub{.interpreted-text role="func"} and ~re.subn{.interpreted-text role="func"} functions now replace unmatched groups with empty strings instead of raising an exception. (Contributed by Serhiy Storchaka in 1519638{.interpreted-text role="issue"}.)

The re.error <re.PatternError>{.interpreted-text role="class"} exceptions have new attributes, ~re.PatternError.msg{.interpreted-text role="attr"}, ~re.PatternError.pattern{.interpreted-text role="attr"}, ~re.PatternError.pos{.interpreted-text role="attr"}, ~re.PatternError.lineno{.interpreted-text role="attr"}, and ~re.PatternError.colno{.interpreted-text role="attr"}, that provide better context information about the error:

>>> re.compile("""
...     (?x)
...     .++
... """)
Traceback (most recent call last):
   ...
sre_constants.error: multiple repeat at position 16 (line 3, column 7)

(Contributed by Serhiy Storchaka in 22578{.interpreted-text role="issue"}.)

readline

A new ~readline.append_history_file{.interpreted-text role="func"} function can be used to append the specified number of trailing elements in history to the given file. (Contributed by Bruno Cauet in 22940{.interpreted-text role="issue"}.)

selectors

The new ~selectors.DevpollSelector{.interpreted-text role="class"} supports efficient /dev/poll polling on Solaris. (Contributed by Giampaolo Rodola' in 18931{.interpreted-text role="issue"}.)

shutil

The ~shutil.move{.interpreted-text role="func"} function now accepts a copy_function argument, allowing, for example, the ~shutil.copy{.interpreted-text role="func"} function to be used instead of the default ~shutil.copy2{.interpreted-text role="func"} if there is a need to ignore file metadata when moving. (Contributed by Claudiu Popa in 19840{.interpreted-text role="issue"}.)

The ~shutil.make_archive{.interpreted-text role="func"} function now supports the xztar format. (Contributed by Serhiy Storchaka in 5411{.interpreted-text role="issue"}.)

signal

On Windows, the ~signal.set_wakeup_fd{.interpreted-text role="func"} function now also supports socket handles. (Contributed by Victor Stinner in 22018{.interpreted-text role="issue"}.)

Various SIG* constants in the signal{.interpreted-text role="mod"} module have been converted into Enums <enum>{.interpreted-text role="mod"}. This allows meaningful names to be printed during debugging, instead of integer "magic numbers". (Contributed by Giampaolo Rodola' in 21076{.interpreted-text role="issue"}.)

smtpd

Both the !SMTPServer{.interpreted-text role="class"} and !SMTPChannel{.interpreted-text role="class"} classes now accept a decode_data keyword argument to determine if the DATA portion of the SMTP transaction is decoded using the "utf-8" codec or is instead provided to the !SMTPServer.process_message{.interpreted-text role="meth"} method as a byte string. The default is True for backward compatibility reasons, but will change to False in Python 3.6. If decode_data is set to False, the process_message method must be prepared to accept keyword arguments. (Contributed by Maciej Szulik in 19662{.interpreted-text role="issue"}.)

The !SMTPServer{.interpreted-text role="class"} class now advertises the 8BITMIME extension (6152{.interpreted-text role="rfc"}) if decode_data has been set True. If the client specifies BODY=8BITMIME on the MAIL command, it is passed to !SMTPServer.process_message{.interpreted-text role="meth"} via the mail_options keyword. (Contributed by Milan Oberkirch and R. David Murray in 21795{.interpreted-text role="issue"}.)

The !SMTPServer{.interpreted-text role="class"} class now also supports the SMTPUTF8 extension (6531{.interpreted-text role="rfc"}: Internationalized Email). If the client specified SMTPUTF8 BODY=8BITMIME on the MAIL command, they are passed to !SMTPServer.process_message{.interpreted-text role="meth"} via the mail_options keyword. It is the responsibility of the process_message method to correctly handle the SMTPUTF8 data. (Contributed by Milan Oberkirch in 21725{.interpreted-text role="issue"}.)

It is now possible to provide, directly or via name resolution, IPv6 addresses in the !SMTPServer{.interpreted-text role="class"} constructor, and have it successfully connect. (Contributed by Milan Oberkirch in 14758{.interpreted-text role="issue"}.)

smtplib

A new SMTP.auth() <smtplib.SMTP.auth>{.interpreted-text role="meth"} method provides a convenient way to implement custom authentication mechanisms. (Contributed by Milan Oberkirch in 15014{.interpreted-text role="issue"}.)

The SMTP.set_debuglevel() <smtplib.SMTP.set_debuglevel>{.interpreted-text role="meth"} method now accepts an additional debuglevel (2), which enables timestamps in debug messages. (Contributed by Gavin Chappell and Maciej Szulik in 16914{.interpreted-text role="issue"}.)

Both the SMTP.sendmail() <smtplib.SMTP.sendmail>{.interpreted-text role="meth"} and SMTP.send_message() <smtplib.SMTP.send_message>{.interpreted-text role="meth"} methods now support 6531{.interpreted-text role="rfc"} (SMTPUTF8). (Contributed by Milan Oberkirch and R. David Murray in 22027{.interpreted-text role="issue"}.)

sndhdr

The !what{.interpreted-text role="func"} and !whathdr{.interpreted-text role="func"} functions now return a ~collections.namedtuple{.interpreted-text role="func"}. (Contributed by Claudiu Popa in 18615{.interpreted-text role="issue"}.)

socket

Functions with timeouts now use a monotonic clock, instead of a system clock. (Contributed by Victor Stinner in 22043{.interpreted-text role="issue"}.)

A new socket.sendfile() <socket.socket.sendfile>{.interpreted-text role="meth"} method allows sending a file over a socket by using the high-performance os.sendfile{.interpreted-text role="func"} function on UNIX, resulting in uploads being from 2 to 3 times faster than when using plain socket.send() <socket.socket.send>{.interpreted-text role="meth"}. (Contributed by Giampaolo Rodola' in 17552{.interpreted-text role="issue"}.)

The socket.sendall() <socket.socket.sendall>{.interpreted-text role="meth"} method no longer resets the socket timeout every time bytes are received or sent. The socket timeout is now the maximum total duration to send all data. (Contributed by Victor Stinner in 23853{.interpreted-text role="issue"}.)

The backlog argument of the socket.listen() <socket.socket.listen>{.interpreted-text role="meth"} method is now optional. By default it is set to SOMAXCONN <socket.SOMAXCONN>{.interpreted-text role="data"} or to 128, whichever is less. (Contributed by Charles-François Natali in 21455{.interpreted-text role="issue"}.)

ssl

Memory BIO Support {#whatsnew-sslmemorybio}

(Contributed by Geert Jansen in 21965{.interpreted-text role="issue"}.)

The new ~ssl.SSLObject{.interpreted-text role="class"} class has been added to provide SSL protocol support for cases when the network I/O capabilities of ~ssl.SSLSocket{.interpreted-text role="class"} are not necessary or are suboptimal. SSLObject represents an SSL protocol instance, but does not implement any network I/O methods, and instead provides a memory buffer interface. The new ~ssl.MemoryBIO{.interpreted-text role="class"} class can be used to pass data between Python and an SSL protocol instance.

The memory BIO SSL support is primarily intended to be used in frameworks implementing asynchronous I/O for which ~ssl.SSLSocket{.interpreted-text role="class"}'s readiness model ("select/poll") is inefficient.

A new SSLContext.wrap_bio() <ssl.SSLContext.wrap_bio>{.interpreted-text role="meth"} method can be used to create a new SSLObject instance.

Application-Layer Protocol Negotiation Support

(Contributed by Benjamin Peterson in 20188{.interpreted-text role="issue"}.)

Where OpenSSL support is present, the ssl{.interpreted-text role="mod"} module now implements the Application-Layer Protocol Negotiation TLS extension as described in 7301{.interpreted-text role="rfc"}.

The new SSLContext.set_alpn_protocols() <ssl.SSLContext.set_alpn_protocols>{.interpreted-text role="meth"} can be used to specify which protocols a socket should advertise during the TLS handshake.

The new SSLSocket.selected_alpn_protocol() <ssl.SSLSocket.selected_alpn_protocol>{.interpreted-text role="meth"} returns the protocol that was selected during the TLS handshake. The ~ssl.HAS_ALPN{.interpreted-text role="const"} flag indicates whether ALPN support is present.

Other Changes

There is a new SSLSocket.version() <ssl.SSLSocket.version>{.interpreted-text role="meth"} method to query the actual protocol version in use. (Contributed by Antoine Pitrou in 20421{.interpreted-text role="issue"}.)

The ~ssl.SSLSocket{.interpreted-text role="class"} class now implements a !SSLSocket.sendfile{.interpreted-text role="meth"} method. (Contributed by Giampaolo Rodola' in 17552{.interpreted-text role="issue"}.)

The !SSLSocket.send{.interpreted-text role="meth"} method now raises either the ssl.SSLWantReadError{.interpreted-text role="exc"} or ssl.SSLWantWriteError{.interpreted-text role="exc"} exception on a non-blocking socket if the operation would block. Previously, it would return 0. (Contributed by Nikolaus Rath in 20951{.interpreted-text role="issue"}.)

The ~ssl.cert_time_to_seconds{.interpreted-text role="func"} function now interprets the input time as UTC and not as local time, per 5280{.interpreted-text role="rfc"}. Additionally, the return value is always an int{.interpreted-text role="class"}. (Contributed by Akira Li in 19940{.interpreted-text role="issue"}.)

New !SSLObject.shared_ciphers{.interpreted-text role="meth"} and SSLSocket.shared_ciphers() <ssl.SSLSocket.shared_ciphers>{.interpreted-text role="meth"} methods return the list of ciphers sent by the client during the handshake. (Contributed by Benjamin Peterson in 23186{.interpreted-text role="issue"}.)

The SSLSocket.do_handshake() <ssl.SSLSocket.do_handshake>{.interpreted-text role="meth"}, SSLSocket.read() <ssl.SSLSocket.read>{.interpreted-text role="meth"}, !SSLSocket.shutdown{.interpreted-text role="meth"}, and SSLSocket.write() <ssl.SSLSocket.write>{.interpreted-text role="meth"} methods of the ~ssl.SSLSocket{.interpreted-text role="class"} class no longer reset the socket timeout every time bytes are received or sent. The socket timeout is now the maximum total duration of the method. (Contributed by Victor Stinner in 23853{.interpreted-text role="issue"}.)

The !match_hostname{.interpreted-text role="func"} function now supports matching of IP addresses. (Contributed by Antoine Pitrou in 23239{.interpreted-text role="issue"}.)

sqlite3

The ~sqlite3.Row{.interpreted-text role="class"} class now fully supports the sequence protocol, in particular reversed{.interpreted-text role="func"} iteration and slice indexing. (Contributed by Claudiu Popa in 10203{.interpreted-text role="issue"}; by Lucas Sinclair, Jessica McKellar, and Serhiy Storchaka in 13583{.interpreted-text role="issue"}.)

subprocess {#whatsnew-subprocess}

The new ~subprocess.run{.interpreted-text role="func"} function has been added. It runs the specified command and returns a ~subprocess.CompletedProcess{.interpreted-text role="class"} object, which describes a finished process. The new API is more consistent and is the recommended approach to invoking subprocesses in Python code that does not need to maintain compatibility with earlier Python versions. (Contributed by Thomas Kluyver in 23342{.interpreted-text role="issue"}.)

Examples:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

sys

A new !set_coroutine_wrapper{.interpreted-text role="func"} function allows setting a global hook that will be called whenever a coroutine object <coroutine>{.interpreted-text role="term"} is created by an async def{.interpreted-text role="keyword"} function. A corresponding !get_coroutine_wrapper{.interpreted-text role="func"} can be used to obtain a currently set wrapper. Both functions are provisional <provisional API>{.interpreted-text role="term"}, and are intended for debugging purposes only. (Contributed by Yury Selivanov in 24017{.interpreted-text role="issue"}.)

A new ~sys.is_finalizing{.interpreted-text role="func"} function can be used to check if the Python interpreter is shutting down <interpreter shutdown>{.interpreted-text role="term"}. (Contributed by Antoine Pitrou in 22696{.interpreted-text role="issue"}.)

sysconfig

The name of the user scripts directory on Windows now includes the first two components of the Python version. (Contributed by Paul Moore in 23437{.interpreted-text role="issue"}.)

tarfile

The mode argument of the ~tarfile.open{.interpreted-text role="func"} function now accepts "x" to request exclusive creation. (Contributed by Berker Peksag in 21717{.interpreted-text role="issue"}.)

The TarFile.extractall() <tarfile.TarFile.extractall>{.interpreted-text role="meth"} and TarFile.extract() <tarfile.TarFile.extract>{.interpreted-text role="meth"} methods now take a keyword argument numeric_owner. If set to True, the extracted files and directories will be owned by the numeric uid and gid from the tarfile. If set to False (the default, and the behavior in versions prior to 3.5), they will be owned by the named user and group in the tarfile. (Contributed by Michael Vogt and Eric Smith in 23193{.interpreted-text role="issue"}.)

The TarFile.list() <tarfile.TarFile.list>{.interpreted-text role="meth"} now accepts an optional members keyword argument that can be set to a subset of the list returned by TarFile.getmembers() <tarfile.TarFile.getmembers>{.interpreted-text role="meth"}. (Contributed by Serhiy Storchaka in 21549{.interpreted-text role="issue"}.)

threading

Both the Lock.acquire() <threading.Lock.acquire>{.interpreted-text role="meth"} and RLock.acquire() <threading.RLock.acquire>{.interpreted-text role="meth"} methods now use a monotonic clock for timeout management. (Contributed by Victor Stinner in 22043{.interpreted-text role="issue"}.)

time

The ~time.monotonic{.interpreted-text role="func"} function is now always available. (Contributed by Victor Stinner in 22043{.interpreted-text role="issue"}.)

timeit

A new command line option -u or --unit={U}{.interpreted-text role="samp"} can be used to specify the time unit for the timer output. Supported options are usec, msec, or sec. (Contributed by Julian Gindi in 18983{.interpreted-text role="issue"}.)

The ~timeit.timeit{.interpreted-text role="func"} function has a new globals parameter for specifying the namespace in which the code will be running. (Contributed by Ben Roberts in 2527{.interpreted-text role="issue"}.)

tkinter

The !tkinter._fix{.interpreted-text role="mod"} module used for setting up the Tcl/Tk environment on Windows has been replaced by a private function in the !_tkinter{.interpreted-text role="mod"} module which makes no permanent changes to environment variables. (Contributed by Zachary Ware in 20035{.interpreted-text role="issue"}.)

traceback {#whatsnew-traceback}

New ~traceback.walk_stack{.interpreted-text role="func"} and ~traceback.walk_tb{.interpreted-text role="func"} functions to conveniently traverse frame and traceback objects <traceback-objects>{.interpreted-text role="ref"}. (Contributed by Robert Collins in 17911{.interpreted-text role="issue"}.)

New lightweight classes: ~traceback.TracebackException{.interpreted-text role="class"}, ~traceback.StackSummary{.interpreted-text role="class"}, and ~traceback.FrameSummary{.interpreted-text role="class"}. (Contributed by Robert Collins in 17911{.interpreted-text role="issue"}.)

Both the ~traceback.print_tb{.interpreted-text role="func"} and ~traceback.print_stack{.interpreted-text role="func"} functions now support negative values for the limit argument. (Contributed by Dmitry Kazakov in 22619{.interpreted-text role="issue"}.)

types

A new ~types.coroutine{.interpreted-text role="func"} function to transform generator <generator iterator>{.interpreted-text role="term"} and generator-like <collections.abc.Generator>{.interpreted-text role="class"} objects into awaitables <awaitable>{.interpreted-text role="term"}. (Contributed by Yury Selivanov in 24017{.interpreted-text role="issue"}.)

A new type called ~types.CoroutineType{.interpreted-text role="class"}, which is used for coroutine{.interpreted-text role="term"} objects created by async def{.interpreted-text role="keyword"} functions. (Contributed by Yury Selivanov in 24400{.interpreted-text role="issue"}.)

unicodedata

The unicodedata{.interpreted-text role="mod"} module now uses data from Unicode 8.0.0.

unittest

The TestLoader.loadTestsFromModule() <unittest.TestLoader.loadTestsFromModule>{.interpreted-text role="meth"} method now accepts a keyword-only argument pattern which is passed to load_tests as the third argument. Found packages are now checked for load_tests regardless of whether their path matches pattern, because it is impossible for a package name to match the default pattern. (Contributed by Robert Collins and Barry A. Warsaw in 16662{.interpreted-text role="issue"}.)

Unittest discovery errors now are exposed in the TestLoader.errors <unittest.TestLoader.errors>{.interpreted-text role="data"} attribute of the ~unittest.TestLoader{.interpreted-text role="class"} instance. (Contributed by Robert Collins in 19746{.interpreted-text role="issue"}.)

A new command line option --locals to show local variables in tracebacks. (Contributed by Robert Collins in 22936{.interpreted-text role="issue"}.)

unittest.mock

The ~unittest.mock.Mock{.interpreted-text role="class"} class has the following improvements:

  • The class constructor has a new unsafe parameter, which causes mock objects to raise AttributeError{.interpreted-text role="exc"} on attribute names starting with "assert". (Contributed by Kushal Das in 21238{.interpreted-text role="issue"}.)
  • A new Mock.assert_not_called() <unittest.mock.Mock.assert_not_called>{.interpreted-text role="meth"} method to check if the mock object was called. (Contributed by Kushal Das in 21262{.interpreted-text role="issue"}.)

The ~unittest.mock.MagicMock{.interpreted-text role="class"} class now supports ~object.__truediv__{.interpreted-text role="meth"}, ~object.__divmod__{.interpreted-text role="meth"} and ~object.__matmul__{.interpreted-text role="meth"} operators. (Contributed by Johannes Baiter in 20968{.interpreted-text role="issue"}, and Håkan Lövdahl in 23581{.interpreted-text role="issue"} and 23568{.interpreted-text role="issue"}.)

It is no longer necessary to explicitly pass create=True to the ~unittest.mock.patch{.interpreted-text role="func"} function when patching builtin names. (Contributed by Kushal Das in 17660{.interpreted-text role="issue"}.)

urllib

A new request.HTTPPasswordMgrWithPriorAuth <urllib.request.HTTPPasswordMgrWithPriorAuth>{.interpreted-text role="class"} class allows HTTP Basic Authentication credentials to be managed so as to eliminate unnecessary 401 response handling, or to unconditionally send credentials on the first request in order to communicate with servers that return a 404 response instead of a 401 if the Authorization header is not sent. (Contributed by Matej Cepl in 19494{.interpreted-text role="issue"} and Akshit Khurana in 7159{.interpreted-text role="issue"}.)

A new quote_via argument for the parse.urlencode() <urllib.parse.urlencode>{.interpreted-text role="func"} function provides a way to control the encoding of query parts if needed. (Contributed by Samwyse and Arnon Yaari in 13866{.interpreted-text role="issue"}.)

The request.urlopen() <urllib.request.urlopen>{.interpreted-text role="func"} function accepts an ssl.SSLContext{.interpreted-text role="class"} object as a context argument, which will be used for the HTTPS connection. (Contributed by Alex Gaynor in 22366{.interpreted-text role="issue"}.)

The parse.urljoin() <urllib.parse.urljoin>{.interpreted-text role="func"} was updated to use the 3986{.interpreted-text role="rfc"} semantics for the resolution of relative URLs, rather than 1808{.interpreted-text role="rfc"} and 2396{.interpreted-text role="rfc"}. (Contributed by Demian Brecht and Senthil Kumaran in 22118{.interpreted-text role="issue"}.)

wsgiref

The headers argument of the headers.Headers <wsgiref.headers.Headers>{.interpreted-text role="class"} class constructor is now optional. (Contributed by Pablo Torres Navarrete and SilentGhost in 5800{.interpreted-text role="issue"}.)

xmlrpc

The client.ServerProxy <xmlrpc.client.ServerProxy>{.interpreted-text role="class"} class now supports the context manager{.interpreted-text role="term"} protocol. (Contributed by Claudiu Popa in 20627{.interpreted-text role="issue"}.)

The client.ServerProxy <xmlrpc.client.ServerProxy>{.interpreted-text role="class"} constructor now accepts an optional ssl.SSLContext{.interpreted-text role="class"} instance. (Contributed by Alex Gaynor in 22960{.interpreted-text role="issue"}.)

xml.sax

SAX parsers now support a character stream of the xmlreader.InputSource <xml.sax.xmlreader.InputSource>{.interpreted-text role="class"} object. (Contributed by Serhiy Storchaka in 2175{.interpreted-text role="issue"}.)

~xml.sax.parseString{.interpreted-text role="func"} now accepts a str{.interpreted-text role="class"} instance. (Contributed by Serhiy Storchaka in 10590{.interpreted-text role="issue"}.)

zipfile

ZIP output can now be written to unseekable streams. (Contributed by Serhiy Storchaka in 23252{.interpreted-text role="issue"}.)

The mode argument of ZipFile.open() <zipfile.ZipFile.open>{.interpreted-text role="meth"} method now accepts "x" to request exclusive creation. (Contributed by Serhiy Storchaka in 21717{.interpreted-text role="issue"}.)

Other module-level changes

Many functions in the mmap{.interpreted-text role="mod"}, !ossaudiodev{.interpreted-text role="mod"}, socket{.interpreted-text role="mod"}, ssl{.interpreted-text role="mod"}, and codecs{.interpreted-text role="mod"} modules now accept writable bytes-like objects <bytes-like object>{.interpreted-text role="term"}. (Contributed by Serhiy Storchaka in 23001{.interpreted-text role="issue"}.)

Optimizations

The os.walk{.interpreted-text role="func"} function has been sped up by 3 to 5 times on POSIX systems, and by 7 to 20 times on Windows. This was done using the new os.scandir{.interpreted-text role="func"} function, which exposes file information from the underlying readdir or FindFirstFile/FindNextFile system calls. (Contributed by Ben Hoyt with help from Victor Stinner in 23605{.interpreted-text role="issue"}.)

Construction of bytes(int) (filled by zero bytes) is faster and uses less memory for large objects. calloc() is used instead of malloc() to allocate memory for these objects. (Contributed by Victor Stinner in 21233{.interpreted-text role="issue"}.)

Some operations on ipaddress{.interpreted-text role="mod"} ~ipaddress.IPv4Network{.interpreted-text role="class"} and ~ipaddress.IPv6Network{.interpreted-text role="class"} have been massively sped up, such as ~ipaddress.IPv4Network.subnets{.interpreted-text role="meth"}, ~ipaddress.IPv4Network.supernet{.interpreted-text role="meth"}, ~ipaddress.summarize_address_range{.interpreted-text role="func"}, ~ipaddress.collapse_addresses{.interpreted-text role="func"}. The speed up can range from 3 to 15 times. (Contributed by Antoine Pitrou, Michel Albert, and Markus in 21486{.interpreted-text role="issue"}, 21487{.interpreted-text role="issue"}, 20826{.interpreted-text role="issue"}, 23266{.interpreted-text role="issue"}.)

Pickling of ipaddress{.interpreted-text role="mod"} objects was optimized to produce significantly smaller output. (Contributed by Serhiy Storchaka in 23133{.interpreted-text role="issue"}.)

Many operations on io.BytesIO{.interpreted-text role="class"} are now 50% to 100% faster. (Contributed by Serhiy Storchaka in 15381{.interpreted-text role="issue"} and David Wilson in 22003{.interpreted-text role="issue"}.)

The marshal.dumps{.interpreted-text role="func"} function is now faster: 65--85% with versions 3 and 4, 20--25% with versions 0 to 2 on typical data, and up to 5 times in best cases. (Contributed by Serhiy Storchaka in 20416{.interpreted-text role="issue"} and 23344{.interpreted-text role="issue"}.)

The UTF-32 encoder is now 3 to 7 times faster. (Contributed by Serhiy Storchaka in 15027{.interpreted-text role="issue"}.)

Regular expressions are now parsed up to 10% faster. (Contributed by Serhiy Storchaka in 19380{.interpreted-text role="issue"}.)

The json.dumps{.interpreted-text role="func"} function was optimized to run with ensure_ascii=False as fast as with ensure_ascii=True. (Contributed by Naoki Inada in 23206{.interpreted-text role="issue"}.)

The PyObject_IsInstance{.interpreted-text role="c:func"} and PyObject_IsSubclass{.interpreted-text role="c:func"} functions have been sped up in the common case that the second argument has type{.interpreted-text role="class"} as its metaclass. (Contributed Georg Brandl by in 22540{.interpreted-text role="issue"}.)

Method caching was slightly improved, yielding up to 5% performance improvement in some benchmarks. (Contributed by Antoine Pitrou in 22847{.interpreted-text role="issue"}.)

Objects from the random{.interpreted-text role="mod"} module now use 50% less memory on 64-bit builds. (Contributed by Serhiy Storchaka in 23488{.interpreted-text role="issue"}.)

The property{.interpreted-text role="func"} getter calls are up to 25% faster. (Contributed by Joe Jevnik in 23910{.interpreted-text role="issue"}.)

Instantiation of fractions.Fraction{.interpreted-text role="class"} is now up to 30% faster. (Contributed by Stefan Behnel in 22464{.interpreted-text role="issue"}.)

String methods ~str.find{.interpreted-text role="meth"}, ~str.rfind{.interpreted-text role="meth"}, ~str.split{.interpreted-text role="meth"}, ~str.partition{.interpreted-text role="meth"} and the in{.interpreted-text role="keyword"} string operator are now significantly faster for searching 1-character substrings. (Contributed by Serhiy Storchaka in 23573{.interpreted-text role="issue"}.)

Build and C API Changes

New calloc functions were added:

  • PyMem_RawCalloc{.interpreted-text role="c:func"},
  • PyMem_Calloc{.interpreted-text role="c:func"},
  • PyObject_Calloc{.interpreted-text role="c:func"}.

(Contributed by Victor Stinner in 21233{.interpreted-text role="issue"}.)

New encoding/decoding helper functions:

  • Py_DecodeLocale{.interpreted-text role="c:func"} (replaced _Py_char2wchar()),
  • Py_EncodeLocale{.interpreted-text role="c:func"} (replaced _Py_wchar2char()).

(Contributed by Victor Stinner in 18395{.interpreted-text role="issue"}.)

A new PyCodec_NameReplaceErrors{.interpreted-text role="c:func"} function to replace the unicode encode error with \N{...} escapes. (Contributed by Serhiy Storchaka in 19676{.interpreted-text role="issue"}.)

A new PyErr_FormatV{.interpreted-text role="c:func"} function similar to PyErr_Format{.interpreted-text role="c:func"}, but accepts a va_list{.interpreted-text role="c:type"} argument. (Contributed by Antoine Pitrou in 18711{.interpreted-text role="issue"}.)

A new PyExc_RecursionError{.interpreted-text role="c:data"} exception. (Contributed by Georg Brandl in 19235{.interpreted-text role="issue"}.)

New PyModule_FromDefAndSpec{.interpreted-text role="c:func"}, PyModule_FromDefAndSpec2{.interpreted-text role="c:func"}, and PyModule_ExecDef{.interpreted-text role="c:func"} functions introduced by 489{.interpreted-text role="pep"} -- multi-phase extension module initialization. (Contributed by Petr Viktorin in 24268{.interpreted-text role="issue"}.)

New PyNumber_MatrixMultiply{.interpreted-text role="c:func"} and PyNumber_InPlaceMatrixMultiply{.interpreted-text role="c:func"} functions to perform matrix multiplication. (Contributed by Benjamin Peterson in 21176{.interpreted-text role="issue"}. See also 465{.interpreted-text role="pep"} for details.)

The PyTypeObject.tp_finalize{.interpreted-text role="c:member"} slot is now part of the stable ABI.

Windows builds now require Microsoft Visual C++ 14.0, which is available as part of Visual Studio 2015.

Extension modules now include a platform information tag in their filename on some platforms (the tag is optional, and CPython will import extensions without it, although if the tag is present and mismatched, the extension won't be loaded):

  • On Linux, extension module filenames end with .cpython-<major><minor>m-<architecture>-<os>.pyd:
    • <major> is the major number of the Python version; for Python 3.5 this is 3.
    • <minor> is the minor number of the Python version; for Python 3.5 this is 5.
    • <architecture> is the hardware architecture the extension module was built to run on. It's most commonly either i386 for 32-bit Intel platforms or x86_64 for 64-bit Intel (and AMD) platforms.
    • <os> is always linux-gnu, except for extensions built to talk to the 32-bit ABI on 64-bit platforms, in which case it is linux-gnu32 (and <architecture> will be x86_64).
  • On Windows, extension module filenames end with <debug>.cp<major><minor>-<platform>.pyd:
    • <major> is the major number of the Python version; for Python 3.5 this is 3.
    • <minor> is the minor number of the Python version; for Python 3.5 this is 5.
    • <platform> is the platform the extension module was built for, either win32 for Win32, win_amd64 for Win64, win_ia64 for Windows Itanium 64, and win_arm for Windows on ARM.
    • If built in debug mode, <debug> will be _d, otherwise it will be blank.
  • On OS X platforms, extension module filenames now end with -darwin.so.
  • On all other platforms, extension module filenames are the same as they were with Python 3.4.

Deprecated

New Keywords

async and await are not recommended to be used as variable, class, function or module names. Introduced by 492{.interpreted-text role="pep"} in Python 3.5, they will become proper keywords in Python 3.7.

Deprecated Python Behavior

Raising the StopIteration{.interpreted-text role="exc"} exception inside a generator will now generate a silent PendingDeprecationWarning{.interpreted-text role="exc"}, which will become a non-silent deprecation warning in Python 3.6 and will trigger a RuntimeError{.interpreted-text role="exc"} in Python 3.7. See PEP 479: Change StopIteration handling inside generators <whatsnew-pep-479>{.interpreted-text role="ref"} for details.

Unsupported Operating Systems

Windows XP is no longer supported by Microsoft, thus, per PEP 11, CPython 3.5 is no longer officially supported on this OS.

Deprecated Python modules, functions and methods

The !formatter{.interpreted-text role="mod"} module has now graduated to full deprecation and is still slated for removal in Python 3.6.

The !asyncio.async{.interpreted-text role="func"} function is deprecated in favor of ~asyncio.ensure_future{.interpreted-text role="func"}.

The !smtpd{.interpreted-text role="mod"} module has in the past always decoded the DATA portion of email messages using the utf-8 codec. This can now be controlled by the new decode_data keyword to !SMTPServer{.interpreted-text role="class"}. The default value is True, but this default is deprecated. Specify the decode_data keyword with an appropriate value to avoid the deprecation warning.

Directly assigning values to the ~http.cookies.Morsel.key{.interpreted-text role="attr"}, ~http.cookies.Morsel.value{.interpreted-text role="attr"} and ~http.cookies.Morsel.coded_value{.interpreted-text role="attr"} of http.cookies.Morsel{.interpreted-text role="class"} objects is deprecated. Use the ~http.cookies.Morsel.set{.interpreted-text role="meth"} method instead. In addition, the undocumented LegalChars parameter of ~http.cookies.Morsel.set{.interpreted-text role="meth"} is deprecated, and is now ignored.

Passing a format string as keyword argument format_string to the ~string.Formatter.format{.interpreted-text role="meth"} method of the string.Formatter{.interpreted-text role="class"} class has been deprecated. (Contributed by Serhiy Storchaka in 23671{.interpreted-text role="issue"}.)

The !platform.dist{.interpreted-text role="func"} and !platform.linux_distribution{.interpreted-text role="func"} functions are now deprecated. Linux distributions use too many different ways of describing themselves, so the functionality is left to a package. (Contributed by Vajrasky Kok and Berker Peksag in 1322{.interpreted-text role="issue"}.)

The previously undocumented from_function and from_builtin methods of inspect.Signature{.interpreted-text role="class"} are deprecated. Use the new Signature.from_callable() <inspect.Signature.from_callable>{.interpreted-text role="meth"} method instead. (Contributed by Yury Selivanov in 24248{.interpreted-text role="issue"}.)

The !inspect.getargspec{.interpreted-text role="func"} function is deprecated and scheduled to be removed in Python 3.6. (See 20438{.interpreted-text role="issue"} for details.)

The inspect{.interpreted-text role="mod"} ~inspect.getfullargspec{.interpreted-text role="func"}, ~inspect.getcallargs{.interpreted-text role="func"}, and !formatargspec{.interpreted-text role="func"} functions are deprecated in favor of the inspect.signature{.interpreted-text role="func"} API. (Contributed by Yury Selivanov in 20438{.interpreted-text role="issue"}.)

~inspect.getargvalues{.interpreted-text role="func"} and ~inspect.formatargvalues{.interpreted-text role="func"} functions were inadvertently marked as deprecated with the release of Python 3.5.0.

Use of re.LOCALE{.interpreted-text role="const"} flag with str patterns or re.ASCII{.interpreted-text role="const"} is now deprecated. (Contributed by Serhiy Storchaka in 22407{.interpreted-text role="issue"}.)

Use of unrecognized special sequences consisting of '\' and an ASCII letter in regular expression patterns and replacement patterns now raises a deprecation warning and will be forbidden in Python 3.6. (Contributed by Serhiy Storchaka in 23622{.interpreted-text role="issue"}.)

The undocumented and unofficial use_load_tests default argument of the unittest.TestLoader.loadTestsFromModule{.interpreted-text role="meth"} method now is deprecated and ignored. (Contributed by Robert Collins and Barry A. Warsaw in 16662{.interpreted-text role="issue"}.)

Removed

API and Feature Removals

The following obsolete and previously deprecated APIs and features have been removed:

  • The __version__ attribute has been dropped from the email package. The email code hasn't been shipped separately from the stdlib for a long time, and the __version__ string was not updated in the last few releases.
  • The internal Netrc class in the ftplib{.interpreted-text role="mod"} module was deprecated in 3.4, and has now been removed. (Contributed by Matt Chaput in 6623{.interpreted-text role="issue"}.)
  • The concept of .pyo files has been removed.
  • The JoinableQueue class in the provisional asyncio{.interpreted-text role="mod"} module was deprecated in 3.4.4 and is now removed. (Contributed by A. Jesse Jiryu Davis in 23464{.interpreted-text role="issue"}.)

Porting to Python 3.5

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in Python behavior

  • Due to an oversight, earlier Python versions erroneously accepted the following syntax:

    f(1 for x in [1], *args)
    f(1 for x in [1], **kwargs)
    

    Python 3.5 now correctly raises a SyntaxError{.interpreted-text role="exc"}, as generator expressions must be put in parentheses if not a sole argument to a function.

Changes in the Python API

  • 475{.interpreted-text role="pep"}: System calls are now retried when interrupted by a signal instead of raising InterruptedError{.interpreted-text role="exc"} if the Python signal handler does not raise an exception.
  • Before Python 3.5, a datetime.time{.interpreted-text role="class"} object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See 13936{.interpreted-text role="issue"} for full details.
  • The !ssl.SSLSocket.send{.interpreted-text role="meth"} method now raises either ssl.SSLWantReadError{.interpreted-text role="exc"} or ssl.SSLWantWriteError{.interpreted-text role="exc"} on a non-blocking socket if the operation would block. Previously, it would return 0. (Contributed by Nikolaus Rath in 20951{.interpreted-text role="issue"}.)
  • The __name__ attribute of generators is now set from the function name, instead of being set from the code name. Use gen.gi_code.co_name to retrieve the code name. Generators also have a new __qualname__ attribute, the qualified name, which is now used for the representation of a generator (repr(gen)). (Contributed by Victor Stinner in 21205{.interpreted-text role="issue"}.)
  • The deprecated "strict" mode and argument of ~html.parser.HTMLParser{.interpreted-text role="class"}, !HTMLParser.error{.interpreted-text role="meth"}, and the !HTMLParserError{.interpreted-text role="exc"} exception have been removed. (Contributed by Ezio Melotti in 15114{.interpreted-text role="issue"}.) The convert_charrefs argument of ~html.parser.HTMLParser{.interpreted-text role="class"} is now True by default. (Contributed by Berker Peksag in 21047{.interpreted-text role="issue"}.)
  • Although it is not formally part of the API, it is worth noting for porting purposes (ie: fixing tests) that error messages that were previously of the form "'sometype' does not support the buffer protocol" are now of the form "a bytes-like object{.interpreted-text role="term"} is required, not 'sometype'". (Contributed by Ezio Melotti in 16518{.interpreted-text role="issue"}.)
  • If the current directory is set to a directory that no longer exists then FileNotFoundError{.interpreted-text role="exc"} will no longer be raised and instead ~importlib.machinery.FileFinder.find_spec{.interpreted-text role="meth"} will return None without caching None in sys.path_importer_cache{.interpreted-text role="data"}, which is different than the typical case (22834{.interpreted-text role="issue"}).
  • HTTP status code and messages from http.client{.interpreted-text role="mod"} and http.server{.interpreted-text role="mod"} were refactored into a common ~http.HTTPStatus{.interpreted-text role="class"} enum. The values in http.client{.interpreted-text role="mod"} and http.server{.interpreted-text role="mod"} remain available for backwards compatibility. (Contributed by Demian Brecht in 21793{.interpreted-text role="issue"}.)
  • When an import loader defines ~importlib.abc.Loader.exec_module{.interpreted-text role="meth"} it is now expected to also define ~importlib.abc.Loader.create_module{.interpreted-text role="meth"} (raises a DeprecationWarning{.interpreted-text role="exc"} now, will be an error in Python 3.6). If the loader inherits from importlib.abc.Loader{.interpreted-text role="class"} then there is nothing to do, else simply define ~importlib.abc.Loader.create_module{.interpreted-text role="meth"} to return None. (Contributed by Brett Cannon in 23014{.interpreted-text role="issue"}.)
  • The re.split{.interpreted-text role="func"} function always ignored empty pattern matches, so the "x*" pattern worked the same as "x+", and the "\b" pattern never worked. Now re.split{.interpreted-text role="func"} raises a warning if the pattern could match an empty string. For compatibility, use patterns that never match an empty string (e.g. "x+" instead of "x*"). Patterns that could only match an empty string (such as "\b") now raise an error. (Contributed by Serhiy Storchaka in 22818{.interpreted-text role="issue"}.)
  • The http.cookies.Morsel{.interpreted-text role="class"} dict-like interface has been made self consistent: morsel comparison now takes the ~http.cookies.Morsel.key{.interpreted-text role="attr"} and ~http.cookies.Morsel.value{.interpreted-text role="attr"} into account, ~http.cookies.Morsel.copy{.interpreted-text role="meth"} now results in a ~http.cookies.Morsel{.interpreted-text role="class"} instance rather than a dict{.interpreted-text role="class"}, and ~http.cookies.Morsel.update{.interpreted-text role="meth"} will now raise an exception if any of the keys in the update dictionary are invalid. In addition, the undocumented LegalChars parameter of ~http.cookies.Morsel.set{.interpreted-text role="func"} is deprecated and is now ignored. (Contributed by Demian Brecht in 2211{.interpreted-text role="issue"}.)
  • 488{.interpreted-text role="pep"} has removed .pyo files from Python and introduced the optional opt- tag in .pyc file names. The importlib.util.cache_from_source{.interpreted-text role="func"} has gained an optimization parameter to help control the opt- tag. Because of this, the debug_override parameter of the function is now deprecated. .pyo files are also no longer supported as a file argument to the Python interpreter and thus serve no purpose when distributed on their own (i.e. sourceless code distribution). Due to the fact that the magic number for bytecode has changed in Python 3.5, all old .pyo files from previous versions of Python are invalid regardless of this PEP.
  • The socket{.interpreted-text role="mod"} module now exports the ~socket.CAN_RAW_FD_FRAMES{.interpreted-text role="const"} constant on linux 3.6 and greater.
  • The ssl.cert_time_to_seconds{.interpreted-text role="func"} function now interprets the input time as UTC and not as local time, per 5280{.interpreted-text role="rfc"}. Additionally, the return value is always an int{.interpreted-text role="class"}. (Contributed by Akira Li in 19940{.interpreted-text role="issue"}.)
  • The pygettext.py Tool now uses the standard +NNNN format for timezones in the POT-Creation-Date header.
  • The smtplib{.interpreted-text role="mod"} module now uses sys.stderr{.interpreted-text role="data"} instead of the previous module-level !stderr{.interpreted-text role="data"} variable for debug output. If your (test) program depends on patching the module-level variable to capture the debug output, you will need to update it to capture sys.stderr instead.
  • The str.startswith{.interpreted-text role="meth"} and str.endswith{.interpreted-text role="meth"} methods no longer return True when finding the empty string and the indexes are completely out of range. (Contributed by Serhiy Storchaka in 24284{.interpreted-text role="issue"}.)
  • The inspect.getdoc{.interpreted-text role="func"} function now returns documentation strings inherited from base classes. Documentation strings no longer need to be duplicated if the inherited documentation is appropriate. To suppress an inherited string, an empty string must be specified (or the documentation may be filled in). This change affects the output of the pydoc{.interpreted-text role="mod"} module and the help{.interpreted-text role="func"} function. (Contributed by Serhiy Storchaka in 15582{.interpreted-text role="issue"}.)
  • Nested functools.partial{.interpreted-text role="func"} calls are now flattened. If you were relying on the previous behavior, you can now either add an attribute to a functools.partial{.interpreted-text role="func"} object or you can create a subclass of functools.partial{.interpreted-text role="func"}. (Contributed by Alexander Belopolsky in 7830{.interpreted-text role="issue"}.)

Changes in the C API

  • The undocumented !format{.interpreted-text role="c:member"} member of the (non-public) !PyMemoryViewObject{.interpreted-text role="c:type"} structure has been removed. All extensions relying on the relevant parts in memoryobject.h must be rebuilt.
  • The !PyMemAllocator{.interpreted-text role="c:type"} structure was renamed to PyMemAllocatorEx{.interpreted-text role="c:type"} and a new calloc field was added.
  • Removed non-documented macro !PyObject_REPR(){.interpreted-text role="c:macro"} which leaked references. Use format character %R in PyUnicode_FromFormat{.interpreted-text role="c:func"}-like functions to format the repr{.interpreted-text role="func"} of the object. (Contributed by Serhiy Storchaka in 22453{.interpreted-text role="issue"}.)
  • Because the lack of the ~type.__module__{.interpreted-text role="attr"} attribute breaks pickling and introspection, a deprecation warning is now raised for builtin types without the ~type.__module__{.interpreted-text role="attr"} attribute. This will be an AttributeError{.interpreted-text role="exc"} in the future. (Contributed by Serhiy Storchaka in 20204{.interpreted-text role="issue"}.)
  • As part of the 492{.interpreted-text role="pep"} implementation, the tp_reserved slot of PyTypeObject{.interpreted-text role="c:type"} was replaced with a ~PyTypeObject.tp_as_async{.interpreted-text role="c:member"} slot. Refer to coro-objects{.interpreted-text role="ref"} for new types, structures and functions.

Notable changes in Python 3.5.4

New make regen-all build target

To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.

Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see Makefile.pre.in{.interpreted-text role="source"} for details.

(Contributed by Victor Stinner in 23404{.interpreted-text role="issue"}.)

::: versionadded 3.5.4 :::

Removal of make touch build target

The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.

It has been replaced by the new make regen-all target.

(Contributed by Victor Stinner in 23404{.interpreted-text role="issue"}.)

::: versionchanged 3.5.4 :::