Generators have a new gi_yieldfrom attribute, which returns the
object being iterated by yieldfrom expressions. (Contributed
by Benno Leslie and Yury Selivanov in issue 24450.)

A new RecursionError exception is now raised when maximum
recursion depth is reached. (Contributed by Georg Brandl
in issue 19235.)

CPython implementation improvements:

When the LC_TYPE locale is the POSIX locale (C locale),
sys.stdin and sys.stdout now use the
surrogateescape error handler, instead of the strict error handler.
(Contributed by Victor Stinner in issue 19977.)

.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.)

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.)

The traceback module has been significantly
enhanced 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
manually. (See issue 22638 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 issue 22796.)

Inside a coroutine function, the new await 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 protocol by
defining the __await__() method.

PEP 465 adds the @ infix operator for matrix multiplication.
Currently, no builtin Python types implement the new operator, however, it
can be implemented by defining __matmul__(), __rmatmul__(),
and __imatmul__() 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:

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.

Function annotation syntax has been a Python feature since version 3.0
(PEP 3107), 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.

PEP 484 introduces a provisional module 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:

defgreeting(name:str)->str:return'Hello '+name

While these annotations are available at runtime through the usual
__annotations__ 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 Any which is consistent with (i.e. assignable to
and from) all types.

PEP 471 adds a new directory iteration function, os.scandir(),
to the standard library. Additionally, os.walk() 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()
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() to display all
the files (excluding directories) in the given path that don’t start with
'.'. The entry.is_file() call will generally
not make an additional system call:

An errno.EINTR error code is returned whenever a system call, that
is waiting for I/O, is interrupted by a signal. Previously, Python would
raise InterruptedError in such cases. This meant that, when writing a
Python application, the developer had two choices:

Ignore the InterruptedError.

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:

PEP 475 implements automatic retry of system calls on
EINTR. This removes the burden of dealing with EINTR
or InterruptedError 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:

The interaction of generators and StopIteration 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.

PEP 479 changes the behavior of generators: when a StopIteration
exception is raised inside a generator, it is replaced with a
RuntimeError before it exits the generator frame. The main goal of
this change is to ease debugging in the situation where an unguarded
next() call raises StopIteration and causes the iteration controlled
by the generator to terminate silently. This is particularly pernicious in
combination with the yieldfrom construct.

This is a backwards incompatible change, so to enable the new behavior,
a __future__ import is necessary:

PEP 485 adds the math.isclose() and cmath.isclose()
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:

PEP 486 makes the Windows launcher (see PEP 397) 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.

PEP 488 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 or -OO. Consequently, bytecode files generated from
-O, and -OO may now exist simultaneously.
importlib.util.cache_from_source() has an updated API to help with
this change.

PEP 489 updates extension module initialization to take advantage of the
two step module loading mechanism introduced by PEP 451 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.

The new zipapp module (specified in PEP 441) provides an API and
command line tool for creating executable Python Zip Applications, which
were introduced in Python 2.6 in issue 1739468, 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
issue 23491.

A new loop.is_closed() method to
check if the event loop is closed.
(Contributed by Victor Stinner in issue 21326.)

A new loop.create_task()
to conveniently create and schedule a new Task
for a coroutine. The create_task method is also used by all
asyncio functions that wrap coroutines into tasks, such as
asyncio.wait(), asyncio.gather(), etc.
(Contributed by Victor Stinner.)

Another new option, -r, allows controlling the maximum recursion
level for subdirectories. (Contributed by Claudiu Popa in issue 19628.)

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 compile_dir(),
compile_file(), and compile_path() can now
accept an integer value indicating the level of output suppression.
(Contributed by Thomas Kluyver in issue 21338.)

configparser now provides a way to customize the conversion
of values by specifying a dictionary of converters in the
ConfigParser constructor, or by defining them
as methods in ConfigParser subclasses. Converters defined in
a parser instance are inherited by its section proxies.

The charset of HTML documents generated by
HtmlDiff.make_file()
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 issue 2052.)

The diff_bytes() function can now compare lists of byte
strings. This fixes a regression from Python 2.
(Contributed by Terry J. Reedy and Greg Ward in issue 17445.)

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

A new policy option EmailPolicy.utf8
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
RFC 6532 and used with an SMTP server that supports the RFC 6531SMTPUTF8 extension. (Contributed by R. David Murray in
issue 24211.)

Element comparison in merge() can now be customized by
passing a key function in a new optional key keyword argument,
and a new optional reverse keyword argument can be used to reverse element
comparison:

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 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 dialog.

The IMAP4 class now supports the context manager protocol.
When used in a with statement, the IMAP4 LOGOUT
command will be called automatically at the end of the block.
(Contributed by Tarek Ziadé and Serhiy Storchaka in issue 4972.)

The what() function now recognizes the
OpenEXR format
(contributed by Martin Vignali and Claudiu Popa in issue 20295),
and the WebP format
(contributed by Fabrice Aneche and Claudiu Popa in issue 20197.)

The util.LazyLoader class allows for
lazy loading of modules in applications where startup time is important.
(Contributed by Brett Cannon in issue 17621.)

The abc.InspectLoader.source_to_code()
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 issue 21156.)

The new util.module_from_spec()
function is now the preferred way to create a new module. As opposed to
creating a types.ModuleType instance directly, this new function
will set the various import-controlled attributes based on the passed-in
spec object. (Contributed by Brett Cannon in issue 20383.)

The signature() 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 issue 20691.)

The json.tool 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 issue 21650.)

A new lazycache() function can be used to capture information
about a non-file-based module to permit getting its lines later via
getline(). 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 issue 17911.)

The handlers.QueueListener 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.)

The new scandir() function returning an iterator of
DirEntry objects has been added. If possible, scandir()
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 issue 22524.)

On Windows, a new
stat_result.st_file_attributes
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 issue 21719.)

The urandom() 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 issue 22181.)

Nested objects, such as unbound methods or nested classes, can now be pickled
using pickle protocols older than protocol version 4.
Protocol version 4 already supports these cases. (Contributed by Serhiy
Storchaka in issue 23611.)

The move() function now accepts a copy_function argument,
allowing, for example, the copy() function to be used instead of
the default copy2() if there is a need to ignore file metadata
when moving.
(Contributed by Claudiu Popa in issue 19840.)

Various SIG* constants in the signal module have been converted into
Enums. This allows meaningful names to be printed
during debugging, instead of integer “magic numbers”.
(Contributed by Giampaolo Rodola’ in issue 21076.)

Both the SMTPServer and SMTPChannel 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()
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 issue 19662.)

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

The SMTPServer class now also supports the SMTPUTF8
extension (RFC 6531: Internationalized Email). If the client specified
SMTPUTF8BODY=8BITMIME on the MAIL command, they are passed to
SMTPServer.process_message()
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 issue 21725.)

It is now possible to provide, directly or via name resolution, IPv6
addresses in the SMTPServer constructor, and have it
successfully connect. (Contributed by Milan Oberkirch in issue 14758.)

The socket.sendall() 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 issue 23853.)

The backlog argument of the socket.listen()
method is now optional. By default it is set to
SOMAXCONN or to 128, whichever is less.
(Contributed by Charles-François Natali in issue 21455.)

The new SSLObject class has been added to provide SSL protocol
support for cases when the network I/O capabilities of SSLSocket
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 MemoryBIO
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 SSLSocket‘s readiness
model (“select/poll”) is inefficient.

The new run() function has been added.
It runs the specified command and returns a
CompletedProcess 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 issue 23342.)

The mode argument of the open() function now accepts "x"
to request exclusive creation. (Contributed by Berker Peksag in issue 21717.)

The TarFile.extractall() and
TarFile.extract() methods now take a keyword
argument numeric_only. 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 issue 23193.)

The tkinter._fix module used for setting up the Tcl/Tk environment
on Windows has been replaced by a private function in the _tkinter
module which makes no permanent changes to environment variables.
(Contributed by Zachary Ware in issue 20035.)

The TestLoader.loadTestsFromModule()
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 issue 16662.)

A new
request.HTTPPasswordMgrWithPriorAuth
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 issue 19494 and Akshit Khurana in
issue 7159.)

A new quote_via argument for the
parse.urlencode()
function provides a way to control the encoding of query parts if needed.
(Contributed by Samwyse and Arnon Yaari in issue 13866.)

The os.walk() 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()
function, which exposes file information from the underlying readdir or
FindFirstFile/FindNextFile system calls. (Contributed by
Ben Hoyt with help from Victor Stinner in issue 23605.)

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 issue 21233.)

The marshal.dumps() 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 issue 20416 and issue 23344.)

The UTF-32 encoder is now 3 to 7 times faster.
(Contributed by Serhiy Storchaka in issue 15027.)

Regular expressions are now parsed up to 10% faster.
(Contributed by Serhiy Storchaka in issue 19380.)

The json.dumps() function was optimized to run with
ensure_ascii=False as fast as with ensure_ascii=True.
(Contributed by Naoki Inada in issue 23206.)

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.

The smtpd 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. The default value is
True, but this default is deprecated. Specify the decode_data keyword
with an appropriate value to avoid the deprecation warning.

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 issue 23622.)

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 module was deprecated in
3.4, and has now been removed.
(Contributed by Matt Chaput in issue 6623.)

The concept of .pyo files has been removed.

The JoinableQueue class in the provisional asyncio module was
deprecated in 3.4.4 and is now removed.
(Contributed by A. Jesse Jiryu Davis in issue 23464.)

PEP 475: System calls are now retried when interrupted by a signal instead
of raising InterruptedError if the Python signal handler does not
raise an exception.

Before Python 3.5, a datetime.time 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 issue 13936 for full
details.

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 issue 21205.)

The deprecated “strict” mode and argument of HTMLParser,
HTMLParser.error(), and the HTMLParserError exception have been
removed. (Contributed by Ezio Melotti in issue 15114.)
The convert_charrefs argument of HTMLParser is
now True by default. (Contributed by Berker Peksag in issue 21047.)

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 is required, not ‘sometype’”.
(Contributed by Ezio Melotti in issue 16518.)

When an import loader defines importlib.machinery.Loader.exec_module()
it is now expected to also define
create_module() (raises a
DeprecationWarning now, will be an error in Python 3.6). If the loader
inherits from importlib.abc.Loader then there is nothing to do, else
simply define create_module() to return
None. (Contributed by Brett Cannon in issue 23014.)

The re.split() function always ignored empty pattern matches, so the
"x*" pattern worked the same as "x+", and the "\b" pattern never
worked. Now re.split() 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 issue 22818.)

The http.cookies.Morsel dict-like interface has been made self
consistent: morsel comparison now takes the key
and value into account,
copy() now results in a
Morsel instance rather than a dict, and
update() will now raise an exception if any of the
keys in the update dictionary are invalid. In addition, the undocumented
LegalChars parameter of set() is deprecated and
is now ignored. (Contributed by Demian Brecht in issue 2211.)

PEP 488 has removed .pyo files from Python and introduced the optional
opt- tag in .pyc file names. The
importlib.util.cache_from_source() 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. sourcless 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 pygettext.py Tool now uses the standard +NNNN format for timezones in
the POT-Creation-Date header.

The smtplib module now uses sys.stderr instead of the previous
module-level stderr 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 inspect.getdoc() 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
module and the help() function.
(Contributed by Serhiy Storchaka in issue 15582.)

The undocumented format member of the
(non-public) PyMemoryViewObject structure has been removed.
All extensions relying on the relevant parts in memoryobject.h
must be rebuilt.

The PyMemAllocator structure was renamed to
PyMemAllocatorEx and a new calloc field was added.

Removed non-documented macro PyObject_REPR which leaked references.
Use format character %R in PyUnicode_FromFormat()-like functions
to format the repr() of the object.
(Contributed by Serhiy Storchaka in issue 22453.)

Because the lack of the __module__ attribute breaks pickling and
introspection, a deprecation warning is now raised for builtin types without
the __module__ attribute. This would be an AttributeError in
the future.
(Contributed by Serhiy Storchaka in issue 20204.)