3 5 RST
3 5 RST
* 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.
* You can comment out your additions if you like, but it's not
necessary (especially when a final release is some months away).
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 <https://docs.python.org/3.5/whatsnew/changelog.html>`_ for a full
list of changes.
.. seealso::
* ``.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 :ref:`PEP 488 overview <whatsnew-pep-488>`.)
* :class:`collections.OrderedDict` is now
:ref:`implemented in C <whatsnew-ordereddict>`, which makes it
4 to 100 times faster.
Security improvements:
Windows improvements:
* Windows builds now use Microsoft Visual C++ 14.0, and extension modules
should use the same.
New Features
============
.. _whatsnew-pep-492:
Coroutine functions are declared using the new :keyword:`async def` syntax::
>>> async def coro():
... return 'spam'
PEP 492 also adds :keyword:`async for` statement for convenient iteration
over asynchronous iterables.
import asyncio
writer.write(b'\r\n'.join([
b'GET / HTTP/1.1',
b'Host: %b' % domain.encode('latin-1'),
b'Connection: close',
b'', b''
]))
writer.close()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(http_get('example.com'))
finally:
loop.close()
import asyncio
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 :keyword:`async for` and :keyword:`async with` can only
be used inside a coroutine function declared with :keyword:`async def`.
.. note::
.. versionchanged:: 3.5.2
Starting with CPython 3.5.2, ``__aiter__`` can directly return
:term:`asynchronous iterators <asynchronous iterator>`. Returning
an :term:`awaitable` object will result in a
:exc:`PendingDeprecationWarning`.
.. seealso::
.. _whatsnew-pep-465:
instead of::
>>> m = numpy.eye(3)
>>> m
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x @ m
array([ 1., 1., 1.])
.. seealso::
.. _whatsnew-pep-448:
>>> *range(4), 4
(0, 1, 2, 3, 4)
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
.. seealso::
.. _whatsnew-pep-461:
Examples::
Note that ``%s`` and ``%r`` conversion types, although supported, should
only be used in codebases that need compatibility with Python 2.
.. seealso::
.. _whatsnew-pep-484:
Function annotation syntax has been a Python feature since version 3.0
(:pep:`3107`), however the semantics of annotations has been left undefined.
For example, here is a simple function whose argument and return type
are declared in the annotations::
The type system supports unions, generic types, and a special type
named :class:`~typing.Any` which is consistent with (i.e. assignable to
and from) all types.
.. seealso::
.. _whatsnew-pep-471:
.. seealso::
:pep:`471` -- os.scandir() function -- a better and faster directory iterator
PEP written and implemented by Ben Hoyt with the help of Victor Stinner.
.. _whatsnew-pep-475:
print("Hello World")
and::
while True:
try:
print("Hello World")
break
except InterruptedError:
continue
* :func:`time.sleep`.
.. seealso::
.. _whatsnew-pep-479:
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
.. seealso::
.. _whatsnew-pep-485:
.. seealso::
.. _whatsnew-pep-486:
.. seealso::
.. _whatsnew-pep-488:
: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
:option:`-O` or :option:`-OO`. Consequently, bytecode files generated from
:option:`-O`, and :option:`-OO` may now exist simultaneously.
:func:`importlib.util.cache_from_source` has an updated API to help with
this change.
.. seealso::
.. _whatsnew-pep-489:
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::
New Modules
===========
typing
------
.. _whatsnew-zipapp:
zipapp
------
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:
.. code-block:: shell-session
.. seealso::
Improved Modules
================
argparse
--------
asyncio
-------
* A new :meth:`transport.get_write_buffer_limits()
<asyncio.WriteTransport.get_write_buffer_limits>`
method to inquire for *high-* and *low-* water limits of the flow
control.
(Contributed by Victor Stinner.)
* New :meth:`loop.set_task_factory()
<asyncio.loop.set_task_factory>` and
:meth:`loop.get_task_factory() <asyncio.loop.get_task_factory>`
methods to customize the task factory that :meth:`loop.create_task()
<asyncio.loop.create_task>` method uses. (Contributed by Yury
Selivanov.)
Updates in 3.5.1:
Updates in 3.5.2:
bz2
---
cgi
---
code
----
The :func:`InteractiveInterpreter.showtraceback()
<code.InteractiveInterpreter.showtraceback>`
method now prints the full chained traceback, just like the interactive
interpreter. (Contributed by Claudiu Popa in :issue:`17442`.)
collections
-----------
.. _whatsnew-ordereddict:
:meth:`OrderedDict.items() <collections.OrderedDict.items>`,
:meth:`OrderedDict.keys() <collections.OrderedDict.keys>`,
:meth:`OrderedDict.values() <collections.OrderedDict.values>` views now support
:func:`reversed` iteration.
(Contributed by Serhiy Storchaka in :issue:`19505`.)
collections.abc
---------------
compileall
----------
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 :func:`~compileall.compile_dir`,
:func:`~compileall.compile_file`, and :func:`~compileall.compile_path` can now
accept an integer value indicating the level of output suppression.
(Contributed by Thomas Kluyver in :issue:`21338`.)
concurrent.futures
------------------
configparser
------------
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']
contextlib
----------
csv
---
curses
------
dbm
---
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 :issue:`5309`.)
doctest
-------
email
-----
A new
:meth:`Message.get_content_disposition()
<email.message.Message.get_content_disposition>`
method provides easy access to a canonical value for the
:mailheader:`Content-Disposition` header.
(Contributed by Abhilash Raj in :issue:`21083`.)
enum
----
faulthandler
------------
functools
---------
.. _whatsnew-lrucache:
glob
----
gzip
----
heapq
-----
Element comparison in :func:`~heapq.merge` can now be customized by
passing a :term:`key function` in a new optional *key* keyword argument,
and a new optional *reverse* keyword argument can be used to reverse element
comparison::
http
----
http.client
-----------
:meth:`HTTPConnection.getresponse() <http.client.HTTPConnection.getresponse>`
now raises a :exc:`~http.client.RemoteDisconnected` exception when a
remote server connection is closed unexpectedly. Additionally, if a
:exc:`ConnectionError` (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
Since idlelib implements the IDLE shell and editor and is not intended for
import by other programs, it gets improvements with every release. See
:file:`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 :menuselection:`Help --> About IDLE` dialog.
imaplib
-------
The :class:`~imaplib.IMAP4` class now supports the :term:`context manager`
protocol.
When used in a :keyword:`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`.)
imghdr
------
importlib
---------
The :func:`abc.InspectLoader.source_to_code()
<importlib.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`.)
inspect
-------
A new
:meth:`BoundArguments.apply_defaults() <inspect.BoundArguments.apply_defaults>`
method provides a way to set default values for missing arguments::
io
--
ipaddress
---------
json
----
The :mod:`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`.)
linecache
---------
locale
------
logging
-------
lzma
----
math
----
Two new constants have been added to the :mod:`math` module: :data:`~math.inf`
and :data:`~math.nan`. (Contributed by Mark Dickinson in :issue:`23185`.)
multiprocessing
---------------
:func:`sharedctypes.synchronized() <multiprocessing.sharedctypes.synchronized>`
objects now support the :term:`context manager` protocol.
(Contributed by Charles-François Natali in :issue:`21565`.)
operator
--------
:func:`~operator.attrgetter`, :func:`~operator.itemgetter`,
and :func:`~operator.methodcaller` objects now support pickling.
(Contributed by Josh Rosenberg and Serhiy Storchaka in :issue:`22955`.)
os
--
On Windows, a new
:attr:`stat_result.st_file_attributes <os.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 :func:`~os.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`.)
pathlib
-------
pickle
------
Nested objects, such as unbound methods or nested classes, can now be pickled
using :ref:`pickle protocols <pickle-protocols>` older than protocol version 4.
Protocol version 4 already supports these cases. (Contributed by Serhiy
Storchaka in :issue:`23611`.)
poplib
------
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'>
>>> re.compile("""
... (?x)
... .++
... """)
Traceback (most recent call last):
...
sre_constants.error: multiple repeat at position 16 (line 3, column 7)
readline
--------
selectors
---------
shutil
------
signal
------
Various ``SIG*`` constants in the :mod:`signal` module have been converted into
:mod:`Enums <enum>`. This allows meaningful names to be printed
during debugging, instead of integer "magic numbers".
(Contributed by Giampaolo Rodola' in :issue:`21076`.)
smtpd
-----
smtplib
-------
sndhdr
------
socket
------
Functions with timeouts now use a monotonic clock, instead of a system clock.
(Contributed by Victor Stinner in :issue:`22043`.)
ssl
---
.. _whatsnew-sslmemorybio:
The new :class:`~ssl.SSLObject` class has been added to provide SSL protocol
support for cases when the network I/O capabilities of :class:`~ssl.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 :class:`~ssl.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 :class:`~ssl.SSLSocket`'s readiness
model ("select/poll") is inefficient.
The new
:meth:`SSLSocket.selected_alpn_protocol() <ssl.SSLSocket.selected_alpn_protocol>`
returns the protocol that was selected during the TLS handshake.
The :data:`~ssl.HAS_ALPN` flag indicates whether ALPN support is present.
Other Changes
~~~~~~~~~~~~~
sqlite3
-------
.. _whatsnew-subprocess:
subprocess
----------
Examples::
sys
---
The name of the user scripts directory on Windows now includes the first
two components of the Python version. (Contributed by Paul Moore
in :issue:`23437`.)
tarfile
-------
threading
---------
time
----
timeit
------
A new command line option ``-u`` or :samp:`--unit={U}` can be used to specify the
time
unit for the timer output. Supported options are ``usec``, ``msec``,
or ``sec``. (Contributed by Julian Gindi in :issue:`18983`.)
tkinter
-------
The :mod:`tkinter._fix` module used for setting up the Tcl/Tk environment
on Windows has been replaced by a private function in the :mod:`_tkinter`
module which makes no permanent changes to environment variables.
(Contributed by Zachary Ware in :issue:`20035`.)
.. _whatsnew-traceback:
traceback
---------
types
-----
unicodedata
-----------
unittest
--------
The :meth:`TestLoader.loadTestsFromModule()
<unittest.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`.)
unittest.mock
-------------
* The class constructor has a new *unsafe* parameter, which causes mock
objects to raise :exc:`AttributeError` on attribute names starting
with ``"assert"``.
(Contributed by Kushal Das in :issue:`21238`.)
urllib
------
A new
:class:`request.HTTPPasswordMgrWithPriorAuth
<urllib.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`.)
xmlrpc
------
xml.sax
-------
zipfile
-------
Optimizations
=============
Objects from the :mod:`random` module now use 50% less memory on 64-bit
builds. (Contributed by Serhiy Storchaka in :issue:`23488`.)
* :c:func:`PyMem_RawCalloc`,
* :c:func:`PyMem_Calloc`,
* :c:func:`PyObject_Calloc`.
* On all other platforms, extension module filenames are the same as they were
with Python 3.4.
Deprecated
==========
New Keywords
------------
The :mod:`formatter` module has now graduated to full deprecation and is still
slated for removal in Python 3.6.
The :mod:`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 :class:`~smtpd.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.
Removed
=======
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.
* :pep:`475`: System calls are now retried when interrupted by a signal instead
of raising :exc:`InterruptedError` if the Python signal handler does not
raise an exception.
* 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`.)
* 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
:term:`bytes-like object` is required, not 'sometype'".
(Contributed by Ezio Melotti in :issue:`16518`.)
* :pep:`488` has removed ``.pyo`` files from Python and introduced the optional
``opt-`` tag in ``.pyc`` file names. The
:func:`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. 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 ``pygettext.py`` Tool now uses the standard +NNNN format for timezones in
the POT-Creation-Date header.
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).
.. versionadded:: 3.5.4
The ``make touch`` build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.
.. versionchanged:: 3.5.4