Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
****************************
What's New In Python 3.11
****************************
:Release: |release|
:Date: |today|
.. Rules for maintenance:
* 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 :issue:`12345`.)
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.11, compared to 3.10.
For full details, see the :ref:`changelog <changelog>`.
.. note::
Prerelease users should be aware that this document is currently in draft
form. It will be updated substantially as Python 3.11 moves towards release,
so it's worth checking back even after reading earlier versions.
Summary -- Release highlights
=============================
.. This section singles out the most important changes in Python 3.11.
Brevity is key.
- Python 3.11 is up to 10-60% faster than Python 3.10. On average, we measured a
Miss Islington (bot)
committed
1.25x speedup on the standard benchmark suite. See `Faster CPython`_ for details.
New syntax features:
* :pep:`654`: Exception Groups and ``except*``.
(Contributed by Irit Katriel in :issue:`45292`.)
New typing features:
* :pep:`646`: Variadic generics.
Miss Islington (bot)
committed
* :pep:`655`: Marking individual TypedDict items as required or potentially missing.
* :pep:`673`: ``Self`` type.
* :pep:`675`: Arbitrary literal string type.
Security improvements:
* New :option:`-P` command line option and :envvar:`PYTHONSAFEPATH` environment
variable to not prepend a potentially unsafe path to :data:`sys.path` such as
the current directory, the script's directory or an empty string.
New Features
============
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
.. _whatsnew311-pep657:
Enhanced error locations in tracebacks
--------------------------------------
When printing tracebacks, the interpreter will now point to the exact expression
that caused the error instead of just the line. For example:
.. code-block:: python
Traceback (most recent call last):
File "distance.py", line 11, in <module>
print(manhattan_distance(p1, p2))
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "distance.py", line 6, in manhattan_distance
return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'x'
Previous versions of the interpreter would point to just the line making it
ambiguous which object was ``None``. These enhanced errors can also be helpful
when dealing with deeply nested dictionary objects and multiple function calls,
.. code-block:: python
Traceback (most recent call last):
File "query.py", line 37, in <module>
magic_arithmetic('foo')
File "query.py", line 18, in magic_arithmetic
return add_counts(x) / 25
^^^^^^^^^^^^^
File "query.py", line 24, in add_counts
return 25 + query_user(user1) + query_user(user2)
^^^^^^^^^^^^^^^^^
File "query.py", line 32, in query_user
return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
~~~~~~~~~~~~~~~~~~^^^^^
TypeError: 'NoneType' object is not subscriptable
as well as complex arithmetic expressions:
.. code-block:: python
Traceback (most recent call last):
File "calculation.py", line 54, in <module>
result = (x / y / z) * (a / b / c)
~~~~~~^~~
ZeroDivisionError: division by zero
See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya
and Ammar Askar in :issue:`43950`.)
.. note::
This feature requires storing column positions in code objects which may
result in a small increase of disk usage of compiled Python files or
interpreter memory usage. To avoid storing the extra information and/or
deactivate printing the extra traceback information, the
:option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES`
environment variable can be used.
Column information for code objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The information used by the enhanced traceback feature is made available as a
general API that can be used to correlate bytecode instructions with source
code. This information can be retrieved using:
- The :meth:`codeobject.co_positions` method in Python.
- The :c:func:`PyCode_Addr2Location` function in the C-API.
The :option:`-X` ``no_debug_ranges`` option and the environment variable
:envvar:`PYTHONNODEBUGRANGES` can be used to disable this feature.
See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya
and Ammar Askar in :issue:`43950`.)
Exceptions can be enriched with notes (PEP 678)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :meth:`add_note` method was added to :exc:`BaseException`. It can be
used to enrich exceptions with context information which is not available
at the time when the exception is raised. The notes added appear in the
default traceback. See :pep:`678` for more details. (Contributed by
Irit Katriel in :issue:`45607`.)
Irit Katriel
committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
.. _new-feat-related-type-hints-311:
New Features Related to Type Hints
==================================
This section covers major changes affecting :pep:`484` type hints and
the :mod:`typing` module.
PEP 646: Variadic generics
--------------------------
:pep:`484` introduced :data:`~typing.TypeVar`, enabling creation
of generics parameterised with a single type. :pep:`646` introduces
:data:`~typing.TypeVarTuple`, enabling parameterisation
with an *arbitrary* number of types. In other words,
a :data:`~typing.TypeVarTuple` is a *variadic* type variable,
enabling *variadic* generics. This enables a wide variety of use cases.
In particular, it allows the type of array-like structures
in numerical computing libraries such as NumPy and TensorFlow to be
parameterised with the array *shape*. Static type checkers will now
be able to catch shape-related bugs in code that uses these libraries.
See :pep:`646` for more details.
(Contributed by Matthew Rahtz in :issue:`43224`, with contributions by
Serhiy Storchaka and Jelle Zijlstra. PEP written by Mark Mendoza, Matthew
Rahtz, Pradeep Kumar Srinivasan, and Vincent Siles.)
PEP 655: Marking individual ``TypedDict`` items as required or not-required
---------------------------------------------------------------------------
:data:`~typing.Required` and :data:`~typing.NotRequired` provide a
straightforward way to mark whether individual items in a
:data:`~typing.TypedDict` must be present. Previously this was only possible
using inheritance.
Fields are still required by default, unless the ``total=False``
parameter is set.
For example, the following specifies a dictionary with one required and
one not-required key::
class Movie(TypedDict):
title: str
year: NotRequired[int]
m1: Movie = {"title": "Black Panther", "year": 2018} # ok
m2: Movie = {"title": "Star Wars"} # ok (year is not required)
m3: Movie = {"year": 2022} # error (missing required field title)
The following definition is equivalent::
class Movie(TypedDict, total=False):
title: Required[str]
year: int
See :pep:`655` for more details.
(Contributed by David Foster and Jelle Zijlstra in :issue:`47087`. PEP
written by David Foster.)
PEP 673: ``Self`` type
----------------------
The new :data:`~typing.Self` annotation provides a simple and intuitive
way to annotate methods that return an instance of their class. This
behaves the same as the :data:`~typing.TypeVar`-based approach specified
in :pep:`484` but is more concise and easier to follow.
Common use cases include alternative constructors provided as classmethods
and :meth:`~object.__enter__` methods that return ``self``::
class MyLock:
def __enter__(self) -> Self:
self.lock()
return self
...
class MyInt:
@classmethod
def fromhex(cls, s: str) -> Self:
return cls(int(s, 16))
...
:data:`~typing.Self` can also be used to annotate method parameters
or attributes of the same type as their enclosing class.
See :pep:`673` for more details.
(Contributed by James Hilton-Balfe in :issue:`46534`. PEP written by
Pradeep Kumar Srinivasan and James Hilton-Balfe.)
PEP 675: Arbitrary literal string type
--------------------------------------
The new :data:`~typing.LiteralString` annotation may be used to indicate
that a function parameter can be of any literal string type. This allows
a function to accept arbitrary literal string types, as well as strings
created from other literal strings. Type checkers can then
enforce that sensitive functions, such as those that execute SQL
statements or shell commands, are called only with static arguments,
providing protection against injection attacks.
For example, a SQL query function could be annotated as follows::
def run_query(sql: LiteralString) -> ...
...
def caller(
arbitrary_string: str,
query_string: LiteralString,
table_name: LiteralString,
) -> None:
run_query("SELECT * FROM students") # ok
run_query(query_string) # ok
run_query("SELECT * FROM " + table_name) # ok
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
See :pep:`675` for more details.
(Contributed by Jelle Zijlstra in :issue:`47088`. PEP written by Pradeep
Kumar Srinivasan and Graham Bleaney.)
PEP 681: Data Class Transforms
------------------------------
:data:`~typing.dataclass_transform` may be used to
decorate a class, metaclass, or a function that is itself a decorator.
The presence of ``@dataclass_transform()`` tells a static type checker that the
decorated object performs runtime "magic" that
transforms a class, giving it :func:`dataclasses.dataclass`-like behaviors.
For example::
# The create_model decorator is defined by a library.
@typing.dataclass_transform()
def create_model(cls: Type[T]) -> Type[T]:
cls.__init__ = ...
cls.__eq__ = ...
cls.__ne__ = ...
return cls
# The create_model decorator can now be used to create new model
# classes, like this:
@create_model
class CustomerModel:
id: int
name: str
c = CustomerModel(id=327, name="John Smith")
See :pep:`681` for more details.
(Contributed by Jelle Zijlstra in :gh:`91860`. PEP written by
Erik De Bonte and Eric Traut.)
Miss Islington (bot)
committed
PEP 563 May Not Be the Future
-----------------------------
* :pep:`563` Postponed Evaluation of Annotations, ``__future__.annotations``
that was planned for this release has been indefinitely postponed.
See `this message <https://mail.python.org/archives/list/python-dev@python.org/message/VIZEBX5EYMSYIJNDBF6DMUMZOCWHARSO/>`_ for more information.
Other Language Changes
======================
Pablo Galindo Salgado
committed
* Starred expressions can be used in :ref:`for statements<for>`. (See
:issue:`46725` for more details.)
Serhiy Storchaka
committed
* Asynchronous comprehensions are now allowed inside comprehensions in
asynchronous functions. Outer comprehensions implicitly become
asynchronous. (Contributed by Serhiy Storchaka in :issue:`33346`.)
* A :exc:`TypeError` is now raised instead of an :exc:`AttributeError` in
:meth:`contextlib.ExitStack.enter_context` and
:meth:`contextlib.AsyncExitStack.enter_async_context` for objects which do not
support the :term:`context manager` or :term:`asynchronous context manager`
protocols correspondingly.
(Contributed by Serhiy Storchaka in :issue:`44471`.)
* A :exc:`TypeError` is now raised instead of an :exc:`AttributeError` in
Serhiy Storchaka
committed
:keyword:`with` and :keyword:`async with` statements for objects which do not
support the :term:`context manager` or :term:`asynchronous context manager`
Serhiy Storchaka
committed
protocols correspondingly.
(Contributed by Serhiy Storchaka in :issue:`12022`.)
* Added :meth:`object.__getstate__` which provides the default
implementation of the ``__getstate__()`` method. :mod:`Copying <copy>`
and :mod:`pickling <pickle>` instances of subclasses of builtin types
:class:`bytearray`, :class:`set`, :class:`frozenset`,
:class:`collections.OrderedDict`, :class:`collections.deque`,
:class:`weakref.WeakSet`, and :class:`datetime.tzinfo` now copies and
pickles instance attributes implemented as :term:`slots <__slots__>`.
(Contributed by Serhiy Storchaka in :issue:`26579`.)
* Add :option:`-P` command line option and :envvar:`PYTHONSAFEPATH` environment
variable to not prepend a potentially unsafe path to :data:`sys.path` such as
the current directory, the script's directory or an empty string.
(Contributed by Victor Stinner in :gh:`57684`.)
* A ``"z"`` option was added to the format specification mini-language that
coerces negative zero to zero after rounding to the format precision. See
:pep:`682` for more details. (Contributed by John Belmonte in :gh:`90153`.)
Miss Islington (bot)
committed
* Bytes are no longer accepted on :attr:`sys.path`. Support broke sometime
between Python 3.2 and 3.6 with no one noticing until after Python 3.10.0
was released. Bringing back support would also be problematic due to
interactions between :option:`-b` and :attr:`sys.path_importer_cache` when
there is a mixture of strings and bytes keys.
(Contributed by Thomas Grainger in :gh:`91181`.)
Other CPython Implementation Changes
====================================
* Special methods :meth:`complex.__complex__` and :meth:`bytes.__bytes__` are implemented to
support :class:`typing.SupportsComplex` and :class:`typing.SupportsBytes` protocols.
(Contributed by Mark Dickinson and Dong-hee Na in :issue:`24234`.)
* ``siphash13`` is added as a new internal hashing algorithms. It has similar security
properties as ``siphash24`` but it is slightly faster for long inputs. ``str``, ``bytes``,
and some other types now use it as default algorithm for :func:`hash`. :pep:`552`
hash-based pyc files now use ``siphash13``, too.
(Contributed by Inada Naoki in :issue:`29410`.)
Irit Katriel
committed
* When an active exception is re-raised by a :keyword:`raise` statement with no parameters,
the traceback attached to this exception is now always ``sys.exc_info()[1].__traceback__``.
This means that changes made to the traceback in the current :keyword:`except` clause are
reflected in the re-raised exception.
(Contributed by Irit Katriel in :issue:`45711`.)
* The interpreter state's representation of handled exceptions (a.k.a exc_info, or
_PyErr_StackItem) now has only the ``exc_value`` field, ``exc_type`` and ``exc_traceback``
have been removed as their values can be derived from ``exc_value``.
(Contributed by Irit Katriel in :issue:`45711`.)
* A new command line option for the Windows installer ``AppendPath`` has been added.
It behaves similiar to ``PrependPath`` but appends the install and scripts directories
(Contributed by Bastian Neuburger in :issue:`44934`.)
Miss Islington (bot)
committed
* The :c:member:`PyConfig.module_search_paths_set` field must now be set to 1 for
initialization to use :c:member:`PyConfig.module_search_paths` to initialize
:data:`sys.path`. Otherwise, initialization will recalculate the path and replace
any values added to ``module_search_paths``.
New Modules
===========
* A new module, :mod:`tomllib`, was added for parsing TOML.
(Contributed by Taneli Hukkinen in :issue:`40059`.)
* :mod:`wsgiref.types`, containing WSGI-specific types for static type
checking, was added.
(Contributed by Sebastian Rittau in :issue:`42012`.)
Improved Modules
================
asyncio
-------
* Add raw datagram socket functions to the event loop:
:meth:`~asyncio.AbstractEventLoop.sock_sendto`,
:meth:`~asyncio.AbstractEventLoop.sock_recvfrom` and
:meth:`~asyncio.AbstractEventLoop.sock_recvfrom_into`.
(Contributed by Alex Grönholm in :issue:`46805`.)
* Add :meth:`~asyncio.streams.StreamWriter.start_tls` method for upgrading
existing stream-based connections to TLS. (Contributed by Ian Good in
:issue:`34975`.)
* Add :class:`~asyncio.Barrier` class to the synchronization primitives of
the asyncio library. (Contributed by Yves Duprat and Andrew Svetlov in
:gh:`87518`.)
* Add :class:`~asyncio.TaskGroup` class,
an :ref:`asynchronous context manager <async-context-managers>`
holding a group of tasks that will wait for all of them upon exit.
(Contributed by Yury Seliganov and others.)
datetime
--------
* Add :attr:`datetime.UTC`, a convenience alias for
:attr:`datetime.timezone.utc`. (Contributed by Kabir Kwatra in :gh:`91973`.)
* :meth:`datetime.date.fromisoformat`, :meth:`datetime.time.fromisoformat` and
:meth:`datetime.datetime.fromisoformat` can now be used to parse most ISO 8601
formats (barring only those that support fractional hours and minutes).
(Contributed by Paul Ganssle in :gh:`80010`.)
Sergey B Kirpichev
committed
fractions
---------
Mark Dickinson
committed
* Support :PEP:`515`-style initialization of :class:`~fractions.Fraction` from
string. (Contributed by Sergey B Kirpichev in :issue:`44258`.)
* :class:`~fractions.Fraction` now implements an ``__int__`` method, so
that an ``isinstance(some_fraction, typing.SupportsInt)`` check passes.
(Contributed by Mark Dickinson in :issue:`44547`.)
Yurii Karabas
committed
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
functools
---------
* :func:`functools.singledispatch` now supports :data:`types.UnionType`
and :data:`typing.Union` as annotations to the dispatch argument.::
>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
... if verbose:
... print("Let me just say,", end=" ")
... print(arg)
...
>>> @fun.register
... def _(arg: int | float, verbose=False):
... if verbose:
... print("Strength in numbers, eh?", end=" ")
... print(arg)
...
>>> from typing import Union
>>> @fun.register
... def _(arg: Union[list, set], verbose=False):
... if verbose:
... print("Enumerate this:")
... for i, elem in enumerate(arg):
... print(i, elem)
...
(Contributed by Yurii Karabas in :issue:`46014`.)
hashlib
-------
* :func:`hashlib.blake2b` and :func:`hashlib.blake2s` now prefer `libb2`_
over Python's vendored copy.
(Contributed by Christian Heimes in :issue:`47095`.)
* The internal ``_sha3`` module with SHA3 and SHAKE algorithms now uses
*tiny_sha3* instead of the *Keccak Code Package* to reduce code and binary
size. The :mod:`hashlib` module prefers optimized SHA3 and SHAKE
implementations from OpenSSL. The change affects only installations without
OpenSSL support.
(Contributed by Christian Heimes in :issue:`47098`.)
IDLE and idlelib
----------------
* Apply syntax highlighting to `.pyi` files. (Contributed by Alex
Waygood and Terry Jan Reedy in :issue:`45447`.)
inspect
-------
* Add :func:`inspect.getmembers_static`: return all members without
triggering dynamic lookup via the descriptor protocol. (Contributed by
Weipeng Hong in :issue:`30533`.)
* Add :func:`inspect.ismethodwrapper` for checking if the type of an object is a
:class:`~types.MethodWrapperType`. (Contributed by Hakan Çelik in :issue:`29418`.)
Pablo Galindo Salgado
committed
* Change the frame-related functions in the :mod:`inspect` module to return a
regular object (that is backwards compatible with the old tuple-like
interface) that include the extended :pep:`657` position information (end
line number, column and end column). The affected functions are:
:func:`inspect.getframeinfo`, :func:`inspect.getouterframes`, :func:`inspect.getinnerframes`,
:func:`inspect.stack` and :func:`inspect.trace`. (Contributed by Pablo Galindo in
:gh:`88116`.)
Pablo Galindo Salgado
committed
locale
------
* Add :func:`locale.getencoding` to get the current locale encoding. It is similar to
``locale.getpreferredencoding(False)`` but ignores the
:ref:`Python UTF-8 Mode <utf8-mode>`.
math
----
* Add :func:`math.exp2`: return 2 raised to the power of x.
(Contributed by Gideon Mitchell in :issue:`45917`.)
* Add :func:`math.cbrt`: return the cube root of x.
(Contributed by Ajith Ramachandran in :issue:`44357`.)
* The behaviour of two :func:`math.pow` corner cases was changed, for
consistency with the IEEE 754 specification. The operations
``math.pow(0.0, -math.inf)`` and ``math.pow(-0.0, -math.inf)`` now return
``inf``. Previously they raised :exc:`ValueError`. (Contributed by Mark
Dickinson in :issue:`44339`.)
* The :data:`math.nan` value is now always available.
(Contributed by Victor Stinner in :issue:`46917`.)
operator
--------
* A new function ``operator.call`` has been added, such that
``operator.call(obj, *args, **kwargs) == obj(*args, **kwargs)``.
(Contributed by Antony Lee in :issue:`44019`.)
Dong-hee Na
committed
os
--
* On Windows, :func:`os.urandom` now uses ``BCryptGenRandom()``,
instead of ``CryptGenRandom()`` which is deprecated.
Dong-hee Na
committed
(Contributed by Dong-hee Na in :issue:`44611`.)
Serhiy Storchaka
committed
pathlib
-------
* :meth:`~pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` return only
directories if *pattern* ends with a pathname components separator:
:data:`~os.sep` or :data:`~os.altsep`.
(Contributed by Eisuke Kawasima in :issue:`22276` and :issue:`33392`.)
Serhiy Storchaka
committed
re
--
Serhiy Storchaka
committed
* Atomic grouping (``(?>...)``) and possessive quantifiers (``*+``, ``++``,
Serhiy Storchaka
committed
``?+``, ``{m,n}+``) are now supported in regular expressions.
(Contributed by Jeffrey C. Jacobs and Serhiy Storchaka in :issue:`433030`.)
Dong-hee Na
committed
shutil
------
* Add optional parameter *dir_fd* in :func:`shutil.rmtree`.
(Contributed by Serhiy Storchaka in :issue:`46245`.)
socket
------
* Add CAN Socket support for NetBSD.
(Contributed by Thomas Klausner in :issue:`30512`.)
Irit Katriel
committed
* :meth:`~socket.create_connection` has an option to raise, in case of
failure to connect, an :exc:`ExceptionGroup` containing all errors
instead of only raising the last error.
(Contributed by Irit Katriel in :issue:`29980`.)
Erlend Egeberg Aasland
committed
sqlite3
-------
* You can now disable the authorizer by passing :const:`None` to
:meth:`~sqlite3.Connection.set_authorizer`.
(Contributed by Erlend E. Aasland in :issue:`44491`.)
Erlend Egeberg Aasland
committed
* Collation name :meth:`~sqlite3.Connection.create_collation` can now
contain any Unicode character. Collation names with invalid characters
now raise :exc:`UnicodeEncodeError` instead of :exc:`sqlite3.ProgrammingError`.
(Contributed by Erlend E. Aasland in :issue:`44688`.)
* :mod:`sqlite3` exceptions now include the SQLite extended error code as
Erlend Egeberg Aasland
committed
:attr:`~sqlite3.Error.sqlite_errorcode` and the SQLite error name as
:attr:`~sqlite3.Error.sqlite_errorname`.
(Contributed by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland in
:issue:`16379` and :issue:`24139`.)
Erlend Egeberg Aasland
committed
* Add :meth:`~sqlite3.Connection.setlimit` and
:meth:`~sqlite3.Connection.getlimit` to :class:`sqlite3.Connection` for
setting and getting SQLite limits by connection basis.
(Contributed by Erlend E. Aasland in :issue:`45243`.)
* :mod:`sqlite3` now sets :attr:`sqlite3.threadsafety` based on the default
threading mode the underlying SQLite library has been compiled with.
(Contributed by Erlend E. Aasland in :issue:`45613`.)
Erlend Egeberg Aasland
committed
* :mod:`sqlite3` C callbacks now use unraisable exceptions if callback
tracebacks are enabled. Users can now register an
:func:`unraisable hook handler <sys.unraisablehook>` to improve their debug
experience.
(Contributed by Erlend E. Aasland in :issue:`45828`.)
* Fetch across rollback no longer raises :exc:`~sqlite3.InterfaceError`.
Instead we leave it to the SQLite library to handle these cases.
(Contributed by Erlend E. Aasland in :issue:`44092`.)
Erlend Egeberg Aasland
committed
* Add :meth:`~sqlite3.Connection.serialize` and
:meth:`~sqlite3.Connection.deserialize` to :class:`sqlite3.Connection` for
serializing and deserializing databases.
(Contributed by Erlend E. Aasland in :issue:`41930`.)
Erlend Egeberg Aasland
committed
* Add :meth:`~sqlite3.Connection.create_window_function` to
:class:`sqlite3.Connection` for creating aggregate window functions.
(Contributed by Erlend E. Aasland in :issue:`34916`.)
Erlend Egeberg Aasland
committed
* Add :meth:`~sqlite3.Connection.blobopen` to :class:`sqlite3.Connection`.
:class:`sqlite3.Blob` allows incremental I/O operations on blobs.
(Contributed by Aviv Palivoda and Erlend E. Aasland in :issue:`24905`.)
Erlend Egeberg Aasland
committed
Erlend Egeberg Aasland
committed
Irit Katriel
committed
sys
---
* :func:`sys.exc_info` now derives the ``type`` and ``traceback`` fields
from the ``value`` (the exception instance), so when an exception is
modified while it is being handled, the changes are reflected in
the results of subsequent calls to :func:`exc_info`.
(Contributed by Irit Katriel in :issue:`45711`.)
* Add :func:`sys.exception` which returns the active exception instance
(equivalent to ``sys.exc_info()[1]``).
(Contributed by Irit Katriel in :issue:`46328`.)
Irit Katriel
committed
* Add the :data:`sys.flags.safe_path <sys.flags>` flag.
(Contributed by Victor Stinner in :gh:`57684`.)
Miro Hrončok
committed
sysconfig
---------
* Two new :ref:`installation schemes <installation_paths>`
(*posix_venv*, *nt_venv* and *venv*) were added and are used when Python
creates new virtual environments or when it is running from a virtual
environment.
The first two schemes (*posix_venv* and *nt_venv*) are OS-specific
for non-Windows and Windows, the *venv* is essentially an alias to one of
them according to the OS Python runs on.
This is useful for downstream distributors who modify
:func:`sysconfig.get_preferred_scheme`.
Third party code that creates new virtual environments should use the new
*venv* installation scheme to determine the paths, as does :mod:`venv`.
(Contributed by Miro Hrončok in :issue:`45413`.)
threading
---------
* On Unix, if the ``sem_clockwait()`` function is available in the C library
(glibc 2.30 and newer), the :meth:`threading.Lock.acquire` method now uses
the monotonic clock (:data:`time.CLOCK_MONOTONIC`) for the timeout, rather
than using the system clock (:data:`time.CLOCK_REALTIME`), to not be affected
by system clock changes.
(Contributed by Victor Stinner in :issue:`41710`.)
time
----
Victor Stinner
committed
* On Unix, :func:`time.sleep` now uses the ``clock_nanosleep()`` or
``nanosleep()`` function, if available, which has a resolution of 1 nanosecond
(10\ :sup:`-9` seconds), rather than using ``select()`` which has a resolution
of 1 microsecond (10\ :sup:`-6` seconds).
(Contributed by Benjamin Szőke and Victor Stinner in :issue:`21302`.)
* On Windows 8.1 and newer, :func:`time.sleep` now uses a waitable timer based
on `high-resolution timers
<https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/high-resolution-timers>`_
which has a resolution of 100 nanoseconds (10\ :sup:`-7` seconds). Previously,
it had a resolution of 1 millisecond (10\ :sup:`-3` seconds).
(Contributed by Benjamin Szőke, Dong-hee Na, Eryk Sun and Victor Stinner in :issue:`21302` and :issue:`45429`.)
typing
------
For major changes, see :ref:`new-feat-related-type-hints-311`.
* Add :func:`typing.assert_never` and :class:`typing.Never`.
:func:`typing.assert_never` is useful for asking a type checker to confirm
that a line of code is not reachable. At runtime, it raises an
:exc:`AssertionError`.
(Contributed by Jelle Zijlstra in :gh:`90633`.)
* Add :func:`typing.reveal_type`. This is useful for asking a type checker
what type it has inferred for a given expression. At runtime it prints
the type of the received value.
(Contributed by Jelle Zijlstra in :gh:`90572`.)
* Add :func:`typing.assert_type`. This is useful for asking a type checker
to confirm that the type it has inferred for a given expression matches
the given type. At runtime it simply returns the received value.
(Contributed by Jelle Zijlstra in :gh:`90638`.)
* :data:`typing.TypedDict` types can now be generic. (Contributed by
Samodya Abeysiriwardane in :gh:`89026`.)
* :class:`~typing.NamedTuple` types can now be generic.
(Contributed by Serhiy Storchaka in :issue:`43923`.)
* Allow subclassing of :class:`typing.Any`. This is useful for avoiding
type checker errors related to highly dynamic class, such as mocks.
(Contributed by Shantanu Jain in :gh:`91154`.)
* The :func:`typing.final` decorator now sets the ``__final__`` attributed on
the decorated object.
(Contributed by Jelle Zijlstra in :gh:`90500`.)
* The :func:`typing.get_overloads` function can be used for introspecting
the overloads of a function. :func:`typing.clear_overloads` can be used
to clear all registered overloads of a function.
(Contributed by Jelle Zijlstra in :gh:`89263`.)
Dong-hee Na
committed
* The :meth:`__init__` method of :class:`~typing.Protocol` subclasses
is now preserved. (Contributed by Adrian Garcia Badarasco in :gh:`88970`.)
* The representation of empty tuple types (``Tuple[()]``) is simplified.
This affects introspection, e.g. ``get_args(Tuple[()])`` now evaluates
to ``()`` instead of ``((),)``.
(Contributed by Serhiy Storchaka in :gh:`91137`.)
* Loosen runtime requirements for type annotations by removing the callable
check in the private ``typing._type_check`` function. (Contributed by
Gregory Beauregard in :gh:`90802`.)
* :func:`typing.get_type_hints` now supports evaluating strings as forward
references in :ref:`PEP 585 generic aliases <types-genericalias>`.
(Contributed by Niklas Rosenstein in :gh:`85542`.)
* :func:`typing.get_type_hints` no longer adds :data:`~typing.Optional`
to parameters with ``None`` as a default. (Contributed by Nikita Sobolev
in :gh:`90353`.)
* :func:`typing.get_type_hints` now supports evaluating bare stringified
:data:`~typing.ClassVar` annotations. (Contributed by Gregory Beauregard
in :gh:`90711`.)
* :func:`typing.no_type_check` no longer modifies external classes and functions.
It also now correctly marks classmethods as not to be type checked. (Contributed
by Nikita Sobolev in :gh:`90729`.)
tkinter
-------
* Added method ``info_patchlevel()`` which returns the exact version of
the Tcl library as a named tuple similar to :data:`sys.version_info`.
(Contributed by Serhiy Storchaka in :gh:`91827`.)
unicodedata
-----------
* The Unicode database has been updated to version 14.0.0. (Contributed by Benjamin Peterson in :issue:`45190`).
Erlend Egeberg Aasland
committed
unittest
--------
* Added methods :meth:`~unittest.TestCase.enterContext` and
:meth:`~unittest.TestCase.enterClassContext` of class
:class:`~unittest.TestCase`, method
:meth:`~unittest.IsolatedAsyncioTestCase.enterAsyncContext` of
class :class:`~unittest.IsolatedAsyncioTestCase` and function
:func:`unittest.enterModuleContext`.
(Contributed by Serhiy Storchaka in :issue:`45046`.)
Miro Hrončok
committed
venv
----
* When new Python virtual environments are created, the *venv*
:ref:`sysconfig installation scheme <installation_paths>` is used
to determine the paths inside the environment.
When Python runs in a virtual environment, the same installation scheme
is the default.
That means that downstream distributors can change the default sysconfig install
scheme without changing behavior of virtual environments.
Third party code that also creates new virtual environments should do the same.
(Contributed by Miro Hrončok in :issue:`45413`.)
warnings
--------
* :func:`warnings.catch_warnings` now accepts arguments for :func:`warnings.simplefilter`,
providing a more concise way to locally ignore warnings or convert them to errors.
(Contributed by Zac Hatfield-Dodds in :issue:`47074`.)
zipfile
-------
* Added support for specifying member name encoding for reading
metadata in the zipfile's directory and file headers.
(Contributed by Stephen J. Turnbull and Serhiy Storchaka in :issue:`28080`.)
Miro Hrončok
committed
David CARLIER
committed
fcntl
-----
* On FreeBSD, the :attr:`F_DUP2FD` and :attr:`F_DUP2FD_CLOEXEC` flags respectively
David CARLIER
committed
are supported, the former equals to ``dup2`` usage while the latter set
the ``FD_CLOEXEC`` flag in addition.
Optimizations
=============
* Compiler now optimizes simple C-style formatting with literal format
containing only format codes ``%s``, ``%r`` and ``%a`` and makes it as
fast as corresponding f-string expression.
(Contributed by Serhiy Storchaka in :issue:`28307`.)
* "Zero-cost" exceptions are implemented. The cost of ``try`` statements is
almost eliminated when no exception is raised.
(Contributed by Mark Shannon in :issue:`40222`.)
* Pure ASCII strings are now normalized in constant time by :func:`unicodedata.normalize`.
(Contributed by Dong-hee Na in :issue:`44987`.)
* :mod:`math` functions :func:`~math.comb` and :func:`~math.perm` are now up
to 10 times or more faster for large arguments (the speed up is larger for
larger *k*).
(Contributed by Serhiy Storchaka in :issue:`37295`.)
* Dict don't store hash value when all inserted keys are Unicode objects.
This reduces dict size. For example, ``sys.getsizeof(dict.fromkeys("abcdefg"))``
becomes 272 bytes from 352 bytes on 64bit platform.
(Contributed by Inada Naoki in :issue:`46845`.)
* :mod:`re`'s regular expression matching engine has been partially refactored,
and now uses computed gotos (or "threaded code") on supported platforms. As a
result, Python 3.11 executes the `pyperformance regular expression benchmarks
<https://pyperformance.readthedocs.io/benchmarks.html#regex-dna>`_ up to 10%
faster than Python 3.10.
Faster CPython
==============
CPython 3.11 is on average `25% faster <https://github.com/faster-cpython/ideas/blob/main/main-vs-310.rst>`_
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
than CPython 3.10 when measured with the
`pyperformance <https://github.com/python/pyperformance>`_ benchmark suite,
and compiled with GCC on Ubuntu Linux. Depending on your workload, the speedup
could be up to 10-60% faster.
This project focuses on two major areas in Python: faster startup and faster
runtime. Other optimizations not under this project are listed in `Optimizations`_.
Faster Startup
--------------
Frozen imports / Static code objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python caches bytecode in the :ref:`__pycache__<tut-pycache>` directory to
speed up module loading.
Previously in 3.10, Python module execution looked like this:
.. code-block:: text
Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate
In Python 3.11, the core modules essential for Python startup are "frozen".
This means that their code objects (and bytecode) are statically allocated
by the interpreter. This reduces the steps in module execution process to this:
.. code-block:: text
Statically allocated code object -> Evaluate
Interpreter startup is now 10-15% faster in Python 3.11. This has a big
impact for short-running programs using Python.
(Contributed by Eric Snow, Guido van Rossum and Kumar Aditya in numerous issues.)
Faster Runtime
--------------
Cheaper, lazy Python frames
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python frames are created whenever Python calls a Python function. This frame
holds execution information. The following are new frame optimizations:
- Streamlined the frame creation process.
- Avoided memory allocation by generously re-using frame space on the C stack.
- Streamlined the internal frame struct to contain only essential information.
Frames previously held extra debugging and memory management information.
Miss Islington (bot)
committed
Old-style frame objects are now created only when requested by debuggers or
by Python introspection functions such as ``sys._getframe`` or
``inspect.currentframe``. For most user code, no frame objects are
created at all. As a result, nearly all Python functions calls have sped
up significantly. We measured a 3-7% speedup in pyperformance.
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(Contributed by Mark Shannon in :issue:`44590`.)
.. _inline-calls:
Inlined Python function calls
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During a Python function call, Python will call an evaluating C function to
interpret that function's code. This effectively limits pure Python recursion to
what's safe for the C stack.
In 3.11, when CPython detects Python code calling another Python function,
it sets up a new frame, and "jumps" to the new code inside the new frame. This
avoids calling the C interpreting function altogether.
Most Python function calls now consume no C stack space. This speeds up
most of such calls. In simple recursive functions like fibonacci or
factorial, a 1.7x speedup was observed. This also means recursive functions
can recurse significantly deeper (if the user increases the recursion limit).
We measured a 1-3% improvement in pyperformance.
(Contributed by Pablo Galindo and Mark Shannon in :issue:`45256`.)
PEP 659: Specializing Adaptive Interpreter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:pep:`659` is one of the key parts of the faster CPython project. The general
idea is that while Python is a dynamic language, most code has regions where
objects and types rarely change. This concept is known as *type stability*.
At runtime, Python will try to look for common patterns and type stability
in the executing code. Python will then replace the current operation with a
more specialized one. This specialized operation uses fast paths available only
to those use cases/types, which generally outperform their generic
counterparts. This also brings in another concept called *inline caching*, where
Python caches the results of expensive operations directly in the bytecode.
The specializer will also combine certain common instruction pairs into one
superinstruction. This reduces the overhead during execution.
Python will only specialize
when it sees code that is "hot" (executed multiple times). This prevents Python
from wasting time for run-once code. Python can also de-specialize when code is