1****************************
2  What's New In Python 3.11
3****************************
4
5:Release: |release|
6:Date: |today|
7:Editor: Pablo Galindo Salgado
8
9.. Rules for maintenance:
10
11   * Anyone can add text to this document.  Do not spend very much time
12   on the wording of your changes, because your text will probably
13   get rewritten to some degree.
14
15   * The maintainer will go through Misc/NEWS periodically and add
16   changes; it's therefore more important to add your changes to
17   Misc/NEWS than to this file.
18
19   * This is not a complete list of every single change; completeness
20   is the purpose of Misc/NEWS.  Some changes I consider too small
21   or esoteric to include.  If such a change is added to the text,
22   I'll just remove it.  (This is another reason you shouldn't spend
23   too much time on writing your addition.)
24
25   * If you want to draw your new text to the attention of the
26   maintainer, add 'XXX' to the beginning of the paragraph or
27   section.
28
29   * It's OK to just add a fragmentary note about a change.  For
30   example: "XXX Describe the transmogrify() function added to the
31   socket module."  The maintainer will research the change and
32   write the necessary text.
33
34   * You can comment out your additions if you like, but it's not
35   necessary (especially when a final release is some months away).
36
37   * Credit the author of a patch or bugfix.   Just the name is
38   sufficient; the e-mail address isn't necessary.
39
40   * It's helpful to add the bug/patch number as a comment:
41
42   XXX Describe the transmogrify() function added to the socket
43   module.
44   (Contributed by P.Y. Developer in :issue:`12345`.)
45
46   This saves the maintainer the effort of going through the Mercurial log
47   when researching a change.
48
49This article explains the new features in Python 3.11, compared to 3.10.
50
51For full details, see the :ref:`changelog <changelog>`.
52
53
54.. _whatsnew311-summary:
55
56Summary -- Release highlights
57=============================
58
59.. This section singles out the most important changes in Python 3.11.
60   Brevity is key.
61
62* Python 3.11 is between 10-60% faster than Python 3.10.
63  On average, we measured a 1.25x speedup on the standard benchmark suite.
64  See :ref:`whatsnew311-faster-cpython` for details.
65
66.. PEP-sized items next.
67
68New syntax features:
69
70* :ref:`whatsnew311-pep654`
71
72New built-in features:
73
74* :ref:`whatsnew311-pep678`
75
76New standard library modules:
77
78* :pep:`680`: :mod:`tomllib` —
79  Support for parsing `TOML <https://toml.io/>`_ in the Standard Library
80
81Interpreter improvements:
82
83* :ref:`whatsnew311-pep657`
84* New :option:`-P` command line option and :envvar:`PYTHONSAFEPATH` environment
85  variable to :ref:`disable automatically prepending potentially unsafe paths
86  <whatsnew311-pythonsafepath>` to :data:`sys.path`
87
88New typing features:
89
90* :ref:`whatsnew311-pep646`
91* :ref:`whatsnew311-pep655`
92* :ref:`whatsnew311-pep673`
93* :ref:`whatsnew311-pep675`
94* :ref:`whatsnew311-pep681`
95
96Important deprecations, removals and restrictions:
97
98* :pep:`594`:
99  :ref:`Many legacy standard library modules have been deprecated
100  <whatsnew311-pep594>` and will be removed in Python 3.13
101* :pep:`624`:
102  :ref:`Py_UNICODE encoder APIs have been removed <whatsnew311-pep624>`
103* :pep:`670`:
104  :ref:`Macros converted to static inline functions <whatsnew311-pep670>`
105
106
107.. _whatsnew311-features:
108
109New Features
110============
111
112.. _whatsnew311-pep657:
113
114PEP 657: Fine-grained error locations in tracebacks
115---------------------------------------------------
116
117When printing tracebacks, the interpreter will now point to the exact expression
118that caused the error, instead of just the line. For example:
119
120.. code-block:: python
121
122    Traceback (most recent call last):
123      File "distance.py", line 11, in <module>
124        print(manhattan_distance(p1, p2))
125              ^^^^^^^^^^^^^^^^^^^^^^^^^^
126      File "distance.py", line 6, in manhattan_distance
127        return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
128                               ^^^^^^^^^
129    AttributeError: 'NoneType' object has no attribute 'x'
130
131Previous versions of the interpreter would point to just the line, making it
132ambiguous which object was ``None``. These enhanced errors can also be helpful
133when dealing with deeply nested :class:`dict` objects and multiple function calls:
134
135.. code-block:: python
136
137    Traceback (most recent call last):
138      File "query.py", line 37, in <module>
139        magic_arithmetic('foo')
140      File "query.py", line 18, in magic_arithmetic
141        return add_counts(x) / 25
142               ^^^^^^^^^^^^^
143      File "query.py", line 24, in add_counts
144        return 25 + query_user(user1) + query_user(user2)
145                    ^^^^^^^^^^^^^^^^^
146      File "query.py", line 32, in query_user
147        return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
148                                   ~~~~~~~~~~~~~~~~~~^^^^^
149    TypeError: 'NoneType' object is not subscriptable
150
151As well as complex arithmetic expressions:
152
153.. code-block:: python
154
155    Traceback (most recent call last):
156      File "calculation.py", line 54, in <module>
157        result = (x / y / z) * (a / b / c)
158                  ~~~~~~^~~
159    ZeroDivisionError: division by zero
160
161Additionally, the information used by the enhanced traceback feature
162is made available via a general API, that can be used to correlate
163:term:`bytecode` :ref:`instructions <bytecodes>` with source code location.
164This information can be retrieved using:
165
166- The :meth:`codeobject.co_positions` method in Python.
167- The :c:func:`PyCode_Addr2Location` function in the C API.
168
169See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya
170and Ammar Askar in :issue:`43950`.)
171
172.. note::
173   This feature requires storing column positions in :ref:`codeobjects`,
174   which may result in a small increase in interpreter memory usage
175   and disk usage for compiled Python files.
176   To avoid storing the extra information
177   and deactivate printing the extra traceback information,
178   use the :option:`-X no_debug_ranges <-X>` command line option
179   or the :envvar:`PYTHONNODEBUGRANGES` environment variable.
180
181
182.. _whatsnew311-pep654:
183
184PEP 654: Exception Groups and ``except*``
185-----------------------------------------
186
187:pep:`654` introduces language features that enable a program
188to raise and handle multiple unrelated exceptions simultaneously.
189The builtin types :exc:`ExceptionGroup` and :exc:`BaseExceptionGroup`
190make it possible to group exceptions and raise them together,
191and the new :keyword:`except* <except_star>` syntax generalizes
192:keyword:`except` to match subgroups of exception groups.
193
194See :pep:`654` for more details.
195
196(Contributed by Irit Katriel in :issue:`45292`. PEP written by
197Irit Katriel, Yury Selivanov and Guido van Rossum.)
198
199
200.. _whatsnew311-pep678:
201
202PEP 678: Exceptions can be enriched with notes
203----------------------------------------------
204
205The :meth:`~BaseException.add_note` method is added to :exc:`BaseException`.
206It can be used to enrich exceptions with context information
207that is not available at the time when the exception is raised.
208The added notes appear in the default traceback.
209
210See :pep:`678` for more details.
211
212(Contributed by Irit Katriel in :issue:`45607`.
213PEP written by Zac Hatfield-Dodds.)
214
215
216.. _whatsnew311-windows-launcher:
217
218Windows ``py.exe`` launcher improvements
219----------------------------------------
220
221The copy of the :ref:`launcher` included with Python 3.11 has been significantly
222updated. It now supports company/tag syntax as defined in :pep:`514` using the
223``-V:<company>/<tag>`` argument instead of the limited ``-<major>.<minor>``.
224This allows launching distributions other than ``PythonCore``,
225the one hosted on `python.org <https://www.python.org>`_.
226
227When using ``-V:`` selectors, either company or tag can be omitted, but all
228installs will be searched. For example, ``-V:OtherPython/`` will select the
229"best" tag registered for ``OtherPython``, while ``-V:3.11`` or ``-V:/3.11``
230will select the "best" distribution with tag ``3.11``.
231
232When using the legacy ``-<major>``, ``-<major>.<minor>``,
233``-<major>-<bitness>`` or ``-<major>.<minor>-<bitness>`` arguments,
234all existing behaviour should be preserved from past versions,
235and only releases from ``PythonCore`` will be selected.
236However, the ``-64`` suffix now implies "not 32-bit" (not necessarily x86-64),
237as there are multiple supported 64-bit platforms.
23832-bit runtimes are detected by checking the runtime's tag for a ``-32`` suffix.
239All releases of Python since 3.5 have included this in their 32-bit builds.
240
241
242.. _new-feat-related-type-hints-311:
243.. _whatsnew311-typing-features:
244
245New Features Related to Type Hints
246==================================
247
248This section covers major changes affecting :pep:`484` type hints and
249the :mod:`typing` module.
250
251
252.. _whatsnew311-pep646:
253
254PEP 646: Variadic generics
255--------------------------
256
257:pep:`484` previously introduced :data:`~typing.TypeVar`, enabling creation
258of generics parameterised with a single type. :pep:`646` adds
259:data:`~typing.TypeVarTuple`, enabling parameterisation
260with an *arbitrary* number of types. In other words,
261a :data:`~typing.TypeVarTuple` is a *variadic* type variable,
262enabling *variadic* generics.
263
264This enables a wide variety of use cases.
265In particular, it allows the type of array-like structures
266in numerical computing libraries such as NumPy and TensorFlow to be
267parameterised with the array *shape*. Static type checkers will now
268be able to catch shape-related bugs in code that uses these libraries.
269
270See :pep:`646` for more details.
271
272(Contributed by Matthew Rahtz in :issue:`43224`, with contributions by
273Serhiy Storchaka and Jelle Zijlstra. PEP written by Mark Mendoza, Matthew
274Rahtz, Pradeep Kumar Srinivasan, and Vincent Siles.)
275
276
277.. _whatsnew311-pep655:
278
279PEP 655: Marking individual ``TypedDict`` items as required or not-required
280---------------------------------------------------------------------------
281
282:data:`~typing.Required` and :data:`~typing.NotRequired` provide a
283straightforward way to mark whether individual items in a
284:class:`~typing.TypedDict` must be present. Previously, this was only possible
285using inheritance.
286
287All fields are still required by default,
288unless the *total* parameter is set to ``False``,
289in which case all fields are still not-required by default.
290For example, the following specifies a :class:`!TypedDict`
291with one required and one not-required key::
292
293   class Movie(TypedDict):
294      title: str
295      year: NotRequired[int]
296
297   m1: Movie = {"title": "Black Panther", "year": 2018}  # OK
298   m2: Movie = {"title": "Star Wars"}  # OK (year is not required)
299   m3: Movie = {"year": 2022}  # ERROR (missing required field title)
300
301The following definition is equivalent::
302
303   class Movie(TypedDict, total=False):
304      title: Required[str]
305      year: int
306
307See :pep:`655` for more details.
308
309(Contributed by David Foster and Jelle Zijlstra in :issue:`47087`. PEP
310written by David Foster.)
311
312
313.. _whatsnew311-pep673:
314
315PEP 673: ``Self`` type
316----------------------
317
318The new :data:`~typing.Self` annotation provides a simple and intuitive
319way to annotate methods that return an instance of their class. This
320behaves the same as the :class:`~typing.TypeVar`-based approach
321:pep:`specified in PEP 484 <484#annotating-instance-and-class-methods>`,
322but is more concise and easier to follow.
323
324Common use cases include alternative constructors provided as
325:func:`classmethod <classmethod>`\s,
326and :meth:`~object.__enter__` methods that return ``self``::
327
328   class MyLock:
329       def __enter__(self) -> Self:
330           self.lock()
331           return self
332
333       ...
334
335   class MyInt:
336       @classmethod
337       def fromhex(cls, s: str) -> Self:
338           return cls(int(s, 16))
339
340       ...
341
342:data:`~typing.Self` can also be used to annotate method parameters
343or attributes of the same type as their enclosing class.
344
345See :pep:`673` for more details.
346
347(Contributed by James Hilton-Balfe in :issue:`46534`. PEP written by
348Pradeep Kumar Srinivasan and James Hilton-Balfe.)
349
350
351.. _whatsnew311-pep675:
352
353PEP 675: Arbitrary literal string type
354--------------------------------------
355
356The new :data:`~typing.LiteralString` annotation may be used to indicate
357that a function parameter can be of any literal string type. This allows
358a function to accept arbitrary literal string types, as well as strings
359created from other literal strings. Type checkers can then
360enforce that sensitive functions, such as those that execute SQL
361statements or shell commands, are called only with static arguments,
362providing protection against injection attacks.
363
364For example, a SQL query function could be annotated as follows::
365
366   def run_query(sql: LiteralString) -> ...
367       ...
368
369   def caller(
370       arbitrary_string: str,
371       query_string: LiteralString,
372       table_name: LiteralString,
373   ) -> None:
374       run_query("SELECT * FROM students")       # ok
375       run_query(query_string)                   # ok
376       run_query("SELECT * FROM " + table_name)  # ok
377       run_query(arbitrary_string)               # type checker error
378       run_query(                                # type checker error
379           f"SELECT * FROM students WHERE name = {arbitrary_string}"
380       )
381
382See :pep:`675` for more details.
383
384(Contributed by Jelle Zijlstra in :issue:`47088`. PEP written by Pradeep
385Kumar Srinivasan and Graham Bleaney.)
386
387
388.. _whatsnew311-pep681:
389
390PEP 681: Data class transforms
391------------------------------
392
393:data:`~typing.dataclass_transform` may be used to
394decorate a class, metaclass, or a function that is itself a decorator.
395The presence of ``@dataclass_transform()`` tells a static type checker that the
396decorated object performs runtime "magic" that transforms a class,
397giving it :func:`dataclass <dataclasses.dataclass>`-like behaviors.
398
399For example::
400
401    # The create_model decorator is defined by a library.
402    @typing.dataclass_transform()
403    def create_model(cls: Type[T]) -> Type[T]:
404        cls.__init__ = ...
405        cls.__eq__ = ...
406        cls.__ne__ = ...
407        return cls
408
409    # The create_model decorator can now be used to create new model classes:
410    @create_model
411    class CustomerModel:
412        id: int
413        name: str
414
415    c = CustomerModel(id=327, name="Eric Idle")
416
417See :pep:`681` for more details.
418
419(Contributed by Jelle Zijlstra in :gh:`91860`. PEP written by
420Erik De Bonte and Eric Traut.)
421
422
423.. _whatsnew311-pep563-deferred:
424
425PEP 563 may not be the future
426-----------------------------
427
428:pep:`563` Postponed Evaluation of Annotations
429(the ``from __future__ import annotations`` :ref:`future statement <future>`)
430that was originally planned for release in Python 3.10
431has been put on hold indefinitely.
432See `this message from the Steering Council <https://mail.python.org/archives/list/[email protected]/message/VIZEBX5EYMSYIJNDBF6DMUMZOCWHARSO/>`__
433for more information.
434
435
436.. _whatsnew311-other-lang-changes:
437
438Other Language Changes
439======================
440
441* Starred unpacking expressions can now be used in :keyword:`for` statements.
442  (See :issue:`46725` for more details.)
443
444* Asynchronous :ref:`comprehensions <comprehensions>` are now allowed
445  inside comprehensions in :ref:`asynchronous functions <async def>`.
446  Outer comprehensions implicitly become asynchronous in this case.
447  (Contributed by Serhiy Storchaka in :issue:`33346`.)
448
449* A :exc:`TypeError` is now raised instead of an :exc:`AttributeError` in
450  :keyword:`with` statements and :meth:`contextlib.ExitStack.enter_context`
451  for objects that do not support the :term:`context manager` protocol,
452  and in :keyword:`async with` statements and
453  :meth:`contextlib.AsyncExitStack.enter_async_context`
454  for objects not supporting the :term:`asynchronous context manager` protocol.
455  (Contributed by Serhiy Storchaka in :issue:`12022` and :issue:`44471`.)
456
457* Added :meth:`object.__getstate__`, which provides the default
458  implementation of the :meth:`!__getstate__` method. :mod:`copy`\ing
459  and :mod:`pickle`\ing instances of subclasses of builtin types
460  :class:`bytearray`, :class:`set`, :class:`frozenset`,
461  :class:`collections.OrderedDict`, :class:`collections.deque`,
462  :class:`weakref.WeakSet`, and :class:`datetime.tzinfo` now copies and
463  pickles instance attributes implemented as :term:`slots <__slots__>`.
464  (Contributed by Serhiy Storchaka in :issue:`26579`.)
465
466.. _whatsnew311-pythonsafepath:
467
468* Added a :option:`-P` command line option
469  and a :envvar:`PYTHONSAFEPATH` environment variable,
470  which disable the automatic prepending to :data:`sys.path`
471  of the script's directory when running a script,
472  or the current directory when using :option:`-c` and :option:`-m`.
473  This ensures only stdlib and installed modules
474  are picked up by :keyword:`import`,
475  and avoids unintentionally or maliciously shadowing modules
476  with those in a local (and typically user-writable) directory.
477  (Contributed by Victor Stinner in :gh:`57684`.)
478
479* A ``"z"`` option was added to the :ref:`formatspec` that
480  coerces negative to positive zero after rounding to the format precision.
481  See :pep:`682` for more details.
482  (Contributed by John Belmonte in :gh:`90153`.)
483
484* Bytes are no longer accepted on :data:`sys.path`.  Support broke sometime
485  between Python 3.2 and 3.6, with no one noticing until after Python 3.10.0
486  was released. In addition, bringing back support would be problematic due to
487  interactions between :option:`-b` and :data:`sys.path_importer_cache` when
488  there is a mixture of :class:`str` and :class:`bytes` keys.
489  (Contributed by Thomas Grainger in :gh:`91181`.)
490
491
492.. _whatsnew311-other-implementation-changes:
493
494Other CPython Implementation Changes
495====================================
496
497* The special methods :meth:`~object.__complex__` for :class:`complex`
498  and :meth:`~object.__bytes__` for :class:`bytes` are implemented to support
499  the :class:`typing.SupportsComplex` and :class:`typing.SupportsBytes` protocols.
500  (Contributed by Mark Dickinson and Dong-hee Na in :issue:`24234`.)
501
502* ``siphash13`` is added as a new internal hashing algorithm.
503  It has similar security properties as ``siphash24``,
504  but it is slightly faster for long inputs.
505  :class:`str`, :class:`bytes`, and some other types
506  now use it as the default algorithm for :func:`hash`.
507  :pep:`552` :ref:`hash-based .pyc files <pyc-invalidation>`
508  now use ``siphash13`` too.
509  (Contributed by Inada Naoki in :issue:`29410`.)
510
511* When an active exception is re-raised by a :keyword:`raise` statement with no parameters,
512  the traceback attached to this exception is now always ``sys.exc_info()[1].__traceback__``.
513  This means that changes made to the traceback in the current :keyword:`except` clause are
514  reflected in the re-raised exception.
515  (Contributed by Irit Katriel in :issue:`45711`.)
516
517* The interpreter state's representation of handled exceptions
518  (aka ``exc_info`` or ``_PyErr_StackItem``)
519  now only has the ``exc_value`` field; ``exc_type`` and ``exc_traceback``
520  have been removed, as they can be derived from ``exc_value``.
521  (Contributed by Irit Katriel in :issue:`45711`.)
522
523* A new :ref:`command line option <install-quiet-option>`, ``AppendPath``,
524  has been added for the Windows installer.
525  It behaves similarly to ``PrependPath``,
526  but appends the install and scripts directories instead of prepending them.
527  (Contributed by Bastian Neuburger in :issue:`44934`.)
528
529* The :c:member:`PyConfig.module_search_paths_set` field must now be set to ``1`` for
530  initialization to use :c:member:`PyConfig.module_search_paths` to initialize
531  :data:`sys.path`. Otherwise, initialization will recalculate the path and replace
532  any values added to ``module_search_paths``.
533
534* The output of the :option:`--help` option now fits in 50 lines/80 columns.
535  Information about :ref:`Python environment variables <using-on-envvars>`
536  and :option:`-X` options is now available using the respective
537  :option:`--help-env` and :option:`--help-xoptions` flags,
538  and with the new :option:`--help-all`.
539  (Contributed by Éric Araujo in :issue:`46142`.)
540
541* Converting between :class:`int` and :class:`str` in bases other than 2
542  (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
543  now raises a :exc:`ValueError` if the number of digits in string form is
544  above a limit to avoid potential denial of service attacks due to the
545  algorithmic complexity. This is a mitigation for `CVE-2020-10735
546  <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735>`_.
547  This limit can be configured or disabled by environment variable, command
548  line flag, or :mod:`sys` APIs. See the :ref:`integer string conversion
549  length limitation <int_max_str_digits>` documentation.  The default limit
550  is 4300 digits in string form.
551
552
553.. _whatsnew311-new-modules:
554
555New Modules
556===========
557
558* :mod:`tomllib`: For parsing `TOML <https://toml.io/>`_.
559  See :pep:`680` for more details.
560  (Contributed by Taneli Hukkinen in :issue:`40059`.)
561
562* :mod:`wsgiref.types`:
563  :pep:`WSGI <3333>`-specific types for static type checking.
564  (Contributed by Sebastian Rittau in :issue:`42012`.)
565
566
567.. _whatsnew311-improved-modules:
568
569Improved Modules
570================
571
572.. _whatsnew311-asyncio:
573
574asyncio
575-------
576
577* Added the :class:`~asyncio.TaskGroup` class,
578  an :ref:`asynchronous context manager <async-context-managers>`
579  holding a group of tasks that will wait for all of them upon exit.
580  For new code this is recommended over using
581  :func:`~asyncio.create_task` and :func:`~asyncio.gather` directly.
582  (Contributed by Yury Selivanov and others in :gh:`90908`.)
583
584* Added :func:`~asyncio.timeout`, an asynchronous context manager for
585  setting a timeout on asynchronous operations. For new code this is
586  recommended over using :func:`~asyncio.wait_for` directly.
587  (Contributed by Andrew Svetlov in :gh:`90927`.)
588
589* Added the :class:`~asyncio.Runner` class, which exposes the machinery
590  used by :func:`~asyncio.run`.
591  (Contributed by Andrew Svetlov in :gh:`91218`.)
592
593* Added the :class:`~asyncio.Barrier` class to the synchronization
594  primitives in the asyncio library, and the related
595  :exc:`~asyncio.BrokenBarrierError` exception.
596  (Contributed by Yves Duprat and Andrew Svetlov in :gh:`87518`.)
597
598* Added keyword argument *all_errors* to :meth:`asyncio.loop.create_connection`
599  so that multiple connection errors can be raised as an :exc:`ExceptionGroup`.
600
601* Added the :meth:`asyncio.StreamWriter.start_tls` method for
602  upgrading existing stream-based connections to TLS.
603  (Contributed by Ian Good in :issue:`34975`.)
604
605* Added raw datagram socket functions to the event loop:
606  :meth:`~asyncio.loop.sock_sendto`,
607  :meth:`~asyncio.loop.sock_recvfrom` and
608  :meth:`~asyncio.loop.sock_recvfrom_into`.
609  These have implementations in :class:`~asyncio.SelectorEventLoop` and
610  :class:`~asyncio.ProactorEventLoop`.
611  (Contributed by Alex Grönholm in :issue:`46805`.)
612
613* Added :meth:`~asyncio.Task.cancelling` and
614  :meth:`~asyncio.Task.uncancel` methods to :class:`~asyncio.Task`.
615  These are primarily intended for internal use,
616  notably by :class:`~asyncio.TaskGroup`.
617
618
619.. _whatsnew311-contextlib:
620
621contextlib
622----------
623
624* Added non parallel-safe :func:`~contextlib.chdir` context manager to change
625  the current working directory and then restore it on exit. Simple wrapper
626  around :func:`~os.chdir`. (Contributed by Filipe Laíns in :issue:`25625`)
627
628
629.. _whatsnew311-dataclasses:
630
631dataclasses
632-----------
633
634* Change field default mutability check, allowing only defaults which are
635  :term:`hashable` instead of any object which is not an instance of
636  :class:`dict`, :class:`list` or :class:`set`. (Contributed by Eric V. Smith in
637  :issue:`44674`.)
638
639
640.. _whatsnew311-datetime:
641
642datetime
643--------
644
645* Add :attr:`datetime.UTC`, a convenience alias for
646  :attr:`datetime.timezone.utc`. (Contributed by Kabir Kwatra in :gh:`91973`.)
647
648* :meth:`datetime.date.fromisoformat`, :meth:`datetime.time.fromisoformat` and
649  :meth:`datetime.datetime.fromisoformat` can now be used to parse most ISO 8601
650  formats (barring only those that support fractional hours and minutes).
651  (Contributed by Paul Ganssle in :gh:`80010`.)
652
653
654.. _whatsnew311-enum:
655
656enum
657----
658
659* Renamed :class:`!EnumMeta` to :class:`~enum.EnumType`
660  (:class:`!EnumMeta` kept as an alias).
661
662* Added :class:`~enum.StrEnum`,
663  with members that can be used as (and must be) strings.
664
665* Added :class:`~enum.ReprEnum`,
666  which only modifies the :meth:`~object.__repr__` of members
667  while returning their literal values (rather than names)
668  for :meth:`~object.__str__` and :meth:`~object.__format__`
669  (used by :func:`str`, :func:`format` and :term:`f-string`\s).
670
671* Changed :meth:`Enum.__format__() <enum.Enum.__format__>` (the default for
672  :func:`format`, :meth:`str.format` and :term:`f-string`\s) to always produce
673  the same result as :meth:`Enum.__str__()`:  for enums inheriting from
674  :class:`~enum.ReprEnum` it will be the member's value; for all other enums
675  it will be the enum and member name (e.g. ``Color.RED``).
676
677* Added a new *boundary* class parameter to :class:`~enum.Flag` enums
678  and the :class:`~enum.FlagBoundary` enum with its options,
679  to control how to handle out-of-range flag values.
680
681* Added the :func:`~enum.verify` enum decorator
682  and the :class:`~enum.EnumCheck` enum with its options,
683  to check enum classes against several specific constraints.
684
685* Added the :func:`~enum.member` and :func:`~enum.nonmember` decorators,
686  to ensure the decorated object is/is not converted to an enum member.
687
688* Added the :func:`~enum.property` decorator,
689  which works like :func:`property` except for enums.
690  Use this instead of :func:`types.DynamicClassAttribute`.
691
692* Added the :func:`~enum.global_enum` enum decorator,
693  which adjusts :meth:`~object.__repr__` and :meth:`~object.__str__`
694  to show values as members of their module rather than the enum class.
695  For example, ``'re.ASCII'`` for the :data:`~re.ASCII` member
696  of :class:`re.RegexFlag` rather than ``'RegexFlag.ASCII'``.
697
698* Enhanced :class:`~enum.Flag` to support
699  :func:`len`, iteration and :keyword:`in`/:keyword:`not in` on its members.
700  For example, the following now works:
701  ``len(AFlag(3)) == 2 and list(AFlag(3)) == (AFlag.ONE, AFlag.TWO)``
702
703* Changed :class:`~enum.Enum` and :class:`~enum.Flag`
704  so that members are now defined
705  before :meth:`~object.__init_subclass__` is called;
706  :func:`dir` now includes methods, etc., from mixed-in data types.
707
708* Changed :class:`~enum.Flag`
709  to only consider primary values (power of two) canonical
710  while composite values (``3``, ``6``, ``10``, etc.) are considered aliases;
711  inverted flags are coerced to their positive equivalent.
712
713
714.. _whatsnew311-fcntl:
715
716fcntl
717-----
718
719* On FreeBSD, the :data:`!F_DUP2FD` and :data:`!F_DUP2FD_CLOEXEC` flags respectively
720  are supported, the former equals to ``dup2`` usage while the latter set
721  the ``FD_CLOEXEC`` flag in addition.
722
723
724.. _whatsnew311-fractions:
725
726fractions
727---------
728
729* Support :PEP:`515`-style initialization of :class:`~fractions.Fraction` from
730  string.  (Contributed by Sergey B Kirpichev in :issue:`44258`.)
731
732* :class:`~fractions.Fraction` now implements an ``__int__`` method, so
733  that an ``isinstance(some_fraction, typing.SupportsInt)`` check passes.
734  (Contributed by Mark Dickinson in :issue:`44547`.)
735
736
737.. _whatsnew311-functools:
738
739functools
740---------
741
742* :func:`functools.singledispatch` now supports :data:`types.UnionType`
743  and :data:`typing.Union` as annotations to the dispatch argument.::
744
745    >>> from functools import singledispatch
746    >>> @singledispatch
747    ... def fun(arg, verbose=False):
748    ...     if verbose:
749    ...         print("Let me just say,", end=" ")
750    ...     print(arg)
751    ...
752    >>> @fun.register
753    ... def _(arg: int | float, verbose=False):
754    ...     if verbose:
755    ...         print("Strength in numbers, eh?", end=" ")
756    ...     print(arg)
757    ...
758    >>> from typing import Union
759    >>> @fun.register
760    ... def _(arg: Union[list, set], verbose=False):
761    ...     if verbose:
762    ...         print("Enumerate this:")
763    ...     for i, elem in enumerate(arg):
764    ...         print(i, elem)
765    ...
766
767  (Contributed by Yurii Karabas in :issue:`46014`.)
768
769
770.. _whatsnew311-hashlib:
771
772hashlib
773-------
774
775* :func:`hashlib.blake2b` and :func:`hashlib.blake2s` now prefer `libb2`_
776  over Python's vendored copy.
777  (Contributed by Christian Heimes in :issue:`47095`.)
778
779* The internal ``_sha3`` module with SHA3 and SHAKE algorithms now uses
780  *tiny_sha3* instead of the *Keccak Code Package* to reduce code and binary
781  size. The :mod:`hashlib` module prefers optimized SHA3 and SHAKE
782  implementations from OpenSSL. The change affects only installations without
783  OpenSSL support.
784  (Contributed by Christian Heimes in :issue:`47098`.)
785
786* Add :func:`hashlib.file_digest`, a helper function for efficient hashing
787  of files or file-like objects.
788  (Contributed by Christian Heimes in :gh:`89313`.)
789
790
791.. _whatsnew311-idle:
792
793IDLE and idlelib
794----------------
795
796* Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex
797  Waygood and Terry Jan Reedy in :issue:`45447`.)
798
799* Include prompts when saving Shell with inputs and outputs.
800  (Contributed by Terry Jan Reedy in :gh:`95191`.)
801
802
803.. _whatsnew311-inspect:
804
805inspect
806-------
807
808* Add :func:`~inspect.getmembers_static` to return all members without
809  triggering dynamic lookup via the descriptor protocol. (Contributed by
810  Weipeng Hong in :issue:`30533`.)
811
812* Add :func:`~inspect.ismethodwrapper`
813  for checking if the type of an object is a :class:`~types.MethodWrapperType`.
814  (Contributed by Hakan Çelik in :issue:`29418`.)
815
816* Change the frame-related functions in the :mod:`inspect` module to return new
817  :class:`~inspect.FrameInfo` and :class:`~inspect.Traceback` class instances
818  (backwards compatible with the previous :term:`named tuple`-like interfaces)
819  that includes the extended :pep:`657` position information (end
820  line number, column and end column). The affected functions are:
821
822  * :func:`inspect.getframeinfo`
823  * :func:`inspect.getouterframes`
824  * :func:`inspect.getinnerframes`,
825  * :func:`inspect.stack`
826  * :func:`inspect.trace`
827
828  (Contributed by Pablo Galindo in :gh:`88116`.)
829
830
831.. _whatsnew311-locale:
832
833locale
834------
835
836* Add :func:`locale.getencoding` to get the current locale encoding. It is similar to
837  ``locale.getpreferredencoding(False)`` but ignores the
838  :ref:`Python UTF-8 Mode <utf8-mode>`.
839
840
841.. _whatsnew311-logging:
842
843logging
844-------
845
846* Added :func:`~logging.getLevelNamesMapping`
847  to return a mapping from logging level names (e.g. ``'CRITICAL'``)
848  to the values of their corresponding :ref:`levels` (e.g. ``50``, by default).
849  (Contributed by Andrei Kulakovin in :gh:`88024`.)
850
851* Added a :meth:`~logging.handlers.SysLogHandler.createSocket` method
852  to :class:`~logging.handlers.SysLogHandler`, to match
853  :meth:`SocketHandler.createSocket()
854  <logging.handlers.SocketHandler.createSocket>`.
855  It is called automatically during handler initialization
856  and when emitting an event, if there is no active socket.
857  (Contributed by Kirill Pinchuk in :gh:`88457`.)
858
859
860.. _whatsnew311-math:
861
862math
863----
864
865* Add :func:`math.exp2`: return 2 raised to the power of x.
866  (Contributed by Gideon Mitchell in :issue:`45917`.)
867
868* Add :func:`math.cbrt`: return the cube root of x.
869  (Contributed by Ajith Ramachandran in :issue:`44357`.)
870
871* The behaviour of two :func:`math.pow` corner cases was changed, for
872  consistency with the IEEE 754 specification. The operations
873  ``math.pow(0.0, -math.inf)`` and ``math.pow(-0.0, -math.inf)`` now return
874  ``inf``. Previously they raised :exc:`ValueError`. (Contributed by Mark
875  Dickinson in :issue:`44339`.)
876
877* The :data:`math.nan` value is now always available.
878  (Contributed by Victor Stinner in :issue:`46917`.)
879
880
881.. _whatsnew311-operator:
882
883operator
884--------
885
886* A new function ``operator.call`` has been added, such that
887  ``operator.call(obj, *args, **kwargs) == obj(*args, **kwargs)``.
888  (Contributed by Antony Lee in :issue:`44019`.)
889
890
891.. _whatsnew311-os:
892
893os
894--
895
896* On Windows, :func:`os.urandom` now uses ``BCryptGenRandom()``,
897  instead of ``CryptGenRandom()`` which is deprecated.
898  (Contributed by Dong-hee Na in :issue:`44611`.)
899
900
901.. _whatsnew311-pathlib:
902
903pathlib
904-------
905
906* :meth:`~pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` return only
907  directories if *pattern* ends with a pathname components separator:
908  :data:`~os.sep` or :data:`~os.altsep`.
909  (Contributed by Eisuke Kawasima in :issue:`22276` and :issue:`33392`.)
910
911
912.. _whatsnew311-re:
913
914re
915--
916
917* Atomic grouping (``(?>...)``) and possessive quantifiers (``*+``, ``++``,
918  ``?+``, ``{m,n}+``) are now supported in regular expressions.
919  (Contributed by Jeffrey C. Jacobs and Serhiy Storchaka in :issue:`433030`.)
920
921
922.. _whatsnew311-shutil:
923
924shutil
925------
926
927* Add optional parameter *dir_fd* in :func:`shutil.rmtree`.
928  (Contributed by Serhiy Storchaka in :issue:`46245`.)
929
930
931.. _whatsnew311-socket:
932
933socket
934------
935
936* Add CAN Socket support for NetBSD.
937  (Contributed by Thomas Klausner in :issue:`30512`.)
938
939* :meth:`~socket.create_connection` has an option to raise, in case of
940  failure to connect, an :exc:`ExceptionGroup` containing all errors
941  instead of only raising the last error.
942  (Contributed by Irit Katriel in :issue:`29980`.)
943
944
945.. _whatsnew311-sqlite3:
946
947sqlite3
948-------
949
950* You can now disable the authorizer by passing :const:`None` to
951  :meth:`~sqlite3.Connection.set_authorizer`.
952  (Contributed by Erlend E. Aasland in :issue:`44491`.)
953
954* Collation name :meth:`~sqlite3.Connection.create_collation` can now
955  contain any Unicode character.  Collation names with invalid characters
956  now raise :exc:`UnicodeEncodeError` instead of :exc:`sqlite3.ProgrammingError`.
957  (Contributed by Erlend E. Aasland in :issue:`44688`.)
958
959* :mod:`sqlite3` exceptions now include the SQLite extended error code as
960  :attr:`~sqlite3.Error.sqlite_errorcode` and the SQLite error name as
961  :attr:`~sqlite3.Error.sqlite_errorname`.
962  (Contributed by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland in
963  :issue:`16379` and :issue:`24139`.)
964
965* Add :meth:`~sqlite3.Connection.setlimit` and
966  :meth:`~sqlite3.Connection.getlimit` to :class:`sqlite3.Connection` for
967  setting and getting SQLite limits by connection basis.
968  (Contributed by Erlend E. Aasland in :issue:`45243`.)
969
970* :mod:`sqlite3` now sets :attr:`sqlite3.threadsafety` based on the default
971  threading mode the underlying SQLite library has been compiled with.
972  (Contributed by Erlend E. Aasland in :issue:`45613`.)
973
974* :mod:`sqlite3` C callbacks now use unraisable exceptions if callback
975  tracebacks are enabled. Users can now register an
976  :func:`unraisable hook handler <sys.unraisablehook>` to improve their debug
977  experience.
978  (Contributed by Erlend E. Aasland in :issue:`45828`.)
979
980* Fetch across rollback no longer raises :exc:`~sqlite3.InterfaceError`.
981  Instead we leave it to the SQLite library to handle these cases.
982  (Contributed by Erlend E. Aasland in :issue:`44092`.)
983
984* Add :meth:`~sqlite3.Connection.serialize` and
985  :meth:`~sqlite3.Connection.deserialize` to :class:`sqlite3.Connection` for
986  serializing and deserializing databases.
987  (Contributed by Erlend E. Aasland in :issue:`41930`.)
988
989* Add :meth:`~sqlite3.Connection.create_window_function` to
990  :class:`sqlite3.Connection` for creating aggregate window functions.
991  (Contributed by Erlend E. Aasland in :issue:`34916`.)
992
993* Add :meth:`~sqlite3.Connection.blobopen` to :class:`sqlite3.Connection`.
994  :class:`sqlite3.Blob` allows incremental I/O operations on blobs.
995  (Contributed by Aviv Palivoda and Erlend E. Aasland in :issue:`24905`.)
996
997
998.. _whatsnew311-string:
999
1000string
1001------
1002
1003* Add :meth:`~string.Template.get_identifiers`
1004  and :meth:`~string.Template.is_valid` to :class:`string.Template`,
1005  which respectively return all valid placeholders,
1006  and whether any invalid placeholders are present.
1007  (Contributed by Ben Kehoe in :gh:`90465`.)
1008
1009
1010.. _whatsnew311-sys:
1011
1012sys
1013---
1014
1015* :func:`sys.exc_info` now derives the ``type`` and ``traceback`` fields
1016  from the ``value`` (the exception instance), so when an exception is
1017  modified while it is being handled, the changes are reflected in
1018  the results of subsequent calls to :func:`!exc_info`.
1019  (Contributed by Irit Katriel in :issue:`45711`.)
1020
1021* Add :func:`sys.exception` which returns the active exception instance
1022  (equivalent to ``sys.exc_info()[1]``).
1023  (Contributed by Irit Katriel in :issue:`46328`.)
1024
1025* Add the :data:`sys.flags.safe_path <sys.flags>` flag.
1026  (Contributed by Victor Stinner in :gh:`57684`.)
1027
1028
1029.. _whatsnew311-sysconfig:
1030
1031sysconfig
1032---------
1033
1034* Three new :ref:`installation schemes <installation_paths>`
1035  (*posix_venv*, *nt_venv* and *venv*) were added and are used when Python
1036  creates new virtual environments or when it is running from a virtual
1037  environment.
1038  The first two schemes (*posix_venv* and *nt_venv*) are OS-specific
1039  for non-Windows and Windows, the *venv* is essentially an alias to one of
1040  them according to the OS Python runs on.
1041  This is useful for downstream distributors who modify
1042  :func:`sysconfig.get_preferred_scheme`.
1043  Third party code that creates new virtual environments should use the new
1044  *venv* installation scheme to determine the paths, as does :mod:`venv`.
1045  (Contributed by Miro Hrončok in :issue:`45413`.)
1046
1047
1048.. _whatsnew311-tempfile:
1049
1050tempfile
1051--------
1052
1053* :class:`~tempfile.SpooledTemporaryFile` objects now fully implement the methods
1054  of :class:`io.BufferedIOBase` or :class:`io.TextIOBase`
1055  (depending on file mode).
1056  This lets them work correctly with APIs that expect file-like objects,
1057  such as compression modules.
1058  (Contributed by Carey Metcalfe in :gh:`70363`.)
1059
1060
1061.. _whatsnew311-threading:
1062
1063threading
1064---------
1065
1066* On Unix, if the ``sem_clockwait()`` function is available in the C library
1067  (glibc 2.30 and newer), the :meth:`threading.Lock.acquire` method now uses
1068  the monotonic clock (:data:`time.CLOCK_MONOTONIC`) for the timeout, rather
1069  than using the system clock (:data:`time.CLOCK_REALTIME`), to not be affected
1070  by system clock changes.
1071  (Contributed by Victor Stinner in :issue:`41710`.)
1072
1073
1074.. _whatsnew311-time:
1075
1076time
1077----
1078
1079* On Unix, :func:`time.sleep` now uses the ``clock_nanosleep()`` or
1080  ``nanosleep()`` function, if available, which has a resolution of 1 nanosecond
1081  (10\ :sup:`-9` seconds), rather than using ``select()`` which has a resolution
1082  of 1 microsecond (10\ :sup:`-6` seconds).
1083  (Contributed by Benjamin Szőke and Victor Stinner in :issue:`21302`.)
1084
1085* On Windows 8.1 and newer, :func:`time.sleep` now uses a waitable timer based
1086  on `high-resolution timers
1087  <https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/high-resolution-timers>`_
1088  which has a resolution of 100 nanoseconds (10\ :sup:`-7` seconds). Previously,
1089  it had a resolution of 1 millisecond (10\ :sup:`-3` seconds).
1090  (Contributed by Benjamin Szőke, Dong-hee Na, Eryk Sun and Victor Stinner in :issue:`21302` and :issue:`45429`.)
1091
1092
1093.. _whatsnew311-tkinter:
1094
1095tkinter
1096-------
1097
1098* Added method ``info_patchlevel()`` which returns the exact version of
1099  the Tcl library as a named tuple similar to :data:`sys.version_info`.
1100  (Contributed by Serhiy Storchaka in :gh:`91827`.)
1101
1102
1103.. _whatsnew311-traceback:
1104
1105traceback
1106---------
1107
1108* Add :func:`traceback.StackSummary.format_frame_summary` to allow users
1109  to override which frames appear in the traceback, and how they are
1110  formatted.
1111  (Contributed by Ammar Askar in :issue:`44569`.)
1112
1113* Add :func:`traceback.TracebackException.print`, which prints the
1114  formatted :exc:`~traceback.TracebackException` instance to a file.
1115  (Contributed by Irit Katriel in :issue:`33809`.)
1116
1117
1118.. _whatsnew311-typing:
1119
1120typing
1121------
1122
1123For major changes, see :ref:`new-feat-related-type-hints-311`.
1124
1125* Add :func:`typing.assert_never` and :class:`typing.Never`.
1126  :func:`typing.assert_never` is useful for asking a type checker to confirm
1127  that a line of code is not reachable. At runtime, it raises an
1128  :exc:`AssertionError`.
1129  (Contributed by Jelle Zijlstra in :gh:`90633`.)
1130
1131* Add :func:`typing.reveal_type`. This is useful for asking a type checker
1132  what type it has inferred for a given expression. At runtime it prints
1133  the type of the received value.
1134  (Contributed by Jelle Zijlstra in :gh:`90572`.)
1135
1136* Add :func:`typing.assert_type`. This is useful for asking a type checker
1137  to confirm that the type it has inferred for a given expression matches
1138  the given type. At runtime it simply returns the received value.
1139  (Contributed by Jelle Zijlstra in :gh:`90638`.)
1140
1141* :data:`typing.TypedDict` types can now be generic. (Contributed by
1142  Samodya Abeysiriwardane in :gh:`89026`.)
1143
1144* :class:`~typing.NamedTuple` types can now be generic.
1145  (Contributed by Serhiy Storchaka in :issue:`43923`.)
1146
1147* Allow subclassing of :class:`typing.Any`. This is useful for avoiding
1148  type checker errors related to highly dynamic class, such as mocks.
1149  (Contributed by Shantanu Jain in :gh:`91154`.)
1150
1151* The :func:`typing.final` decorator now sets the ``__final__`` attributed on
1152  the decorated object.
1153  (Contributed by Jelle Zijlstra in :gh:`90500`.)
1154
1155* The :func:`typing.get_overloads` function can be used for introspecting
1156  the overloads of a function. :func:`typing.clear_overloads` can be used
1157  to clear all registered overloads of a function.
1158  (Contributed by Jelle Zijlstra in :gh:`89263`.)
1159
1160* The :meth:`~object.__init__` method of :class:`~typing.Protocol` subclasses
1161  is now preserved. (Contributed by Adrian Garcia Badarasco in :gh:`88970`.)
1162
1163* The representation of empty tuple types (``Tuple[()]``) is simplified.
1164  This affects introspection, e.g. ``get_args(Tuple[()])`` now evaluates
1165  to ``()`` instead of ``((),)``.
1166  (Contributed by Serhiy Storchaka in :gh:`91137`.)
1167
1168* Loosen runtime requirements for type annotations by removing the callable
1169  check in the private ``typing._type_check`` function. (Contributed by
1170  Gregory Beauregard in :gh:`90802`.)
1171
1172* :func:`typing.get_type_hints` now supports evaluating strings as forward
1173  references in :ref:`PEP 585 generic aliases <types-genericalias>`.
1174  (Contributed by Niklas Rosenstein in :gh:`85542`.)
1175
1176* :func:`typing.get_type_hints` no longer adds :data:`~typing.Optional`
1177  to parameters with ``None`` as a default. (Contributed by Nikita Sobolev
1178  in :gh:`90353`.)
1179
1180* :func:`typing.get_type_hints` now supports evaluating bare stringified
1181  :data:`~typing.ClassVar` annotations. (Contributed by Gregory Beauregard
1182  in :gh:`90711`.)
1183
1184* :func:`typing.no_type_check` no longer modifies external classes and functions.
1185  It also now correctly marks classmethods as not to be type checked. (Contributed
1186  by Nikita Sobolev in :gh:`90729`.)
1187
1188
1189.. _whatsnew311-unicodedata:
1190
1191unicodedata
1192-----------
1193
1194* The Unicode database has been updated to version 14.0.0.
1195  (Contributed by Benjamin Peterson in :issue:`45190`).
1196
1197
1198.. _whatsnew311-unittest:
1199
1200unittest
1201--------
1202
1203* Added methods :meth:`~unittest.TestCase.enterContext` and
1204  :meth:`~unittest.TestCase.enterClassContext` of class
1205  :class:`~unittest.TestCase`, method
1206  :meth:`~unittest.IsolatedAsyncioTestCase.enterAsyncContext` of
1207  class :class:`~unittest.IsolatedAsyncioTestCase` and function
1208  :func:`unittest.enterModuleContext`.
1209  (Contributed by Serhiy Storchaka in :issue:`45046`.)
1210
1211
1212.. _whatsnew311-venv:
1213
1214venv
1215----
1216
1217* When new Python virtual environments are created, the *venv*
1218  :ref:`sysconfig installation scheme <installation_paths>` is used
1219  to determine the paths inside the environment.
1220  When Python runs in a virtual environment, the same installation scheme
1221  is the default.
1222  That means that downstream distributors can change the default sysconfig install
1223  scheme without changing behavior of virtual environments.
1224  Third party code that also creates new virtual environments should do the same.
1225  (Contributed by Miro Hrončok in :issue:`45413`.)
1226
1227
1228.. _whatsnew311-warnings:
1229
1230warnings
1231--------
1232
1233* :func:`warnings.catch_warnings` now accepts arguments for :func:`warnings.simplefilter`,
1234  providing a more concise way to locally ignore warnings or convert them to errors.
1235  (Contributed by Zac Hatfield-Dodds in :issue:`47074`.)
1236
1237
1238.. _whatsnew311-zipfile:
1239
1240zipfile
1241-------
1242
1243* Added support for specifying member name encoding for reading metadata
1244  in a :class:`~zipfile.ZipFile`'s directory and file headers.
1245  (Contributed by Stephen J. Turnbull and Serhiy Storchaka in :issue:`28080`.)
1246
1247* Added :meth:`ZipFile.mkdir() <zipfile.ZipFile.mkdir>`
1248  for creating new directories inside ZIP archives.
1249  (Contributed by Sam Ezeh in :gh:`49083`.)
1250
1251* Added :attr:`~zipfile.Path.stem`, :attr:`~zipfile.Path.suffix`
1252  and :attr:`~zipfile.Path.suffixes` to :class:`zipfile.Path`.
1253  (Contributed by Miguel Brito in :gh:`88261`.)
1254
1255
1256.. _whatsnew311-optimizations:
1257
1258Optimizations
1259=============
1260
1261This section covers specific optimizations independent of the
1262:ref:`whatsnew311-faster-cpython` project, which is covered in its own section.
1263
1264* The compiler now optimizes simple
1265  :ref:`printf-style % formatting <old-string-formatting>` on string literals
1266  containing only the format codes ``%s``, ``%r`` and ``%a`` and makes it as
1267  fast as a corresponding :term:`f-string` expression.
1268  (Contributed by Serhiy Storchaka in :issue:`28307`.)
1269
1270* Integer division (``//``) is better tuned for optimization by compilers.
1271  It is now around 20% faster on x86-64 when dividing an :class:`int`
1272  by a value smaller than ``2**30``.
1273  (Contributed by Gregory P. Smith and Tim Peters in :gh:`90564`.)
1274
1275* :func:`sum` is now nearly 30% faster for integers smaller than ``2**30``.
1276  (Contributed by Stefan Behnel in :gh:`68264`.)
1277
1278* Resizing lists is streamlined for the common case,
1279  speeding up :meth:`list.append` by ≈15%
1280  and simple :term:`list comprehension`\s by up to 20-30%
1281  (Contributed by Dennis Sweeney in :gh:`91165`.)
1282
1283* Dictionaries don't store hash values when all keys are Unicode objects,
1284  decreasing :class:`dict` size.
1285  For example, ``sys.getsizeof(dict.fromkeys("abcdefg"))``
1286  is reduced from 352 bytes to 272 bytes (23% smaller) on 64-bit platforms.
1287  (Contributed by Inada Naoki in :issue:`46845`.)
1288
1289* Using :class:`asyncio.DatagramProtocol` is now orders of magnitude faster
1290  when transferring large files over UDP,
1291  with speeds over 100 times higher for a ≈60 MiB file.
1292  (Contributed by msoxzw in :gh:`91487`.)
1293
1294* :mod:`math` functions :func:`~math.comb` and :func:`~math.perm` are now
1295  ≈10 times faster for large arguments (with a larger speedup for larger *k*).
1296  (Contributed by Serhiy Storchaka in :issue:`37295`.)
1297
1298* The :mod:`statistics` functions :func:`~statistics.mean`,
1299  :func:`~statistics.variance` and :func:`~statistics.stdev` now consume
1300  iterators in one pass rather than converting them to a :class:`list` first.
1301  This is twice as fast and can save substantial memory.
1302  (Contributed by Raymond Hettinger in :gh:`90415`.)
1303
1304* :func:`unicodedata.normalize`
1305  now normalizes pure-ASCII strings in constant time.
1306  (Contributed by Dong-hee Na in :issue:`44987`.)
1307
1308
1309.. _whatsnew311-faster-cpython:
1310
1311Faster CPython
1312==============
1313
1314CPython 3.11 is an average of
1315`25% faster <https://github.com/faster-cpython/ideas#published-results>`_
1316than CPython 3.10 as measured with the
1317`pyperformance <https://github.com/python/pyperformance>`_ benchmark suite,
1318when compiled with GCC on Ubuntu Linux.
1319Depending on your workload, the overall speedup could be 10-60%.
1320
1321This project focuses on two major areas in Python:
1322:ref:`whatsnew311-faster-startup` and :ref:`whatsnew311-faster-runtime`.
1323Optimizations not covered by this project are listed separately under
1324:ref:`whatsnew311-optimizations`.
1325
1326
1327.. _whatsnew311-faster-startup:
1328
1329Faster Startup
1330--------------
1331
1332.. _whatsnew311-faster-imports:
1333
1334Frozen imports / Static code objects
1335^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1336
1337Python caches :term:`bytecode` in the :ref:`__pycache__ <tut-pycache>`
1338directory to speed up module loading.
1339
1340Previously in 3.10, Python module execution looked like this:
1341
1342.. code-block:: text
1343
1344   Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate
1345
1346In Python 3.11, the core modules essential for Python startup are "frozen".
1347This means that their :ref:`codeobjects` (and bytecode)
1348are statically allocated by the interpreter.
1349This reduces the steps in module execution process to:
1350
1351.. code-block:: text
1352
1353   Statically allocated code object -> Evaluate
1354
1355Interpreter startup is now 10-15% faster in Python 3.11. This has a big
1356impact for short-running programs using Python.
1357
1358(Contributed by Eric Snow, Guido van Rossum and Kumar Aditya in many issues.)
1359
1360
1361.. _whatsnew311-faster-runtime:
1362
1363Faster Runtime
1364--------------
1365
1366.. _whatsnew311-lazy-python-frames:
1367
1368Cheaper, lazy Python frames
1369^^^^^^^^^^^^^^^^^^^^^^^^^^^
1370
1371Python frames, holding execution information,
1372are created whenever Python calls a Python function.
1373The following are new frame optimizations:
1374
1375- Streamlined the frame creation process.
1376- Avoided memory allocation by generously re-using frame space on the C stack.
1377- Streamlined the internal frame struct to contain only essential information.
1378  Frames previously held extra debugging and memory management information.
1379
1380Old-style :ref:`frame objects <frame-objects>`
1381are now created only when requested by debuggers
1382or by Python introspection functions such as :func:`sys._getframe` and
1383:func:`inspect.currentframe`. For most user code, no frame objects are
1384created at all. As a result, nearly all Python functions calls have sped
1385up significantly. We measured a 3-7% speedup in pyperformance.
1386
1387(Contributed by Mark Shannon in :issue:`44590`.)
1388
1389
1390.. _inline-calls:
1391.. _whatsnew311-inline-calls:
1392
1393Inlined Python function calls
1394^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1395
1396During a Python function call, Python will call an evaluating C function to
1397interpret that function's code. This effectively limits pure Python recursion to
1398what's safe for the C stack.
1399
1400In 3.11, when CPython detects Python code calling another Python function,
1401it sets up a new frame, and "jumps" to the new code inside the new frame. This
1402avoids calling the C interpreting function altogether.
1403
1404Most Python function calls now consume no C stack space, speeding them up.
1405In simple recursive functions like fibonacci or
1406factorial, we observed a 1.7x speedup. This also means recursive functions
1407can recurse significantly deeper
1408(if the user increases the recursion limit with :func:`sys.setrecursionlimit`).
1409We measured a 1-3% improvement in pyperformance.
1410
1411(Contributed by Pablo Galindo and Mark Shannon in :issue:`45256`.)
1412
1413
1414.. _whatsnew311-pep659:
1415
1416PEP 659: Specializing Adaptive Interpreter
1417^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1418
1419:pep:`659` is one of the key parts of the Faster CPython project. The general
1420idea is that while Python is a dynamic language, most code has regions where
1421objects and types rarely change. This concept is known as *type stability*.
1422
1423At runtime, Python will try to look for common patterns and type stability
1424in the executing code. Python will then replace the current operation with a
1425more specialized one. This specialized operation uses fast paths available only
1426to those use cases/types, which generally outperform their generic
1427counterparts. This also brings in another concept called *inline caching*, where
1428Python caches the results of expensive operations directly in the
1429:term:`bytecode`.
1430
1431The specializer will also combine certain common instruction pairs into one
1432superinstruction, reducing the overhead during execution.
1433
1434Python will only specialize
1435when it sees code that is "hot" (executed multiple times). This prevents Python
1436from wasting time on run-once code. Python can also de-specialize when code is
1437too dynamic or when the use changes. Specialization is attempted periodically,
1438and specialization attempts are not too expensive,
1439allowing specialization to adapt to new circumstances.
1440
1441(PEP written by Mark Shannon, with ideas inspired by Stefan Brunthaler.
1442See :pep:`659` for more information. Implementation by Mark Shannon and Brandt
1443Bucher, with additional help from Irit Katriel and Dennis Sweeney.)
1444
1445..
1446   If I missed out anyone, please add them.
1447
1448+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1449| Operation     | Form               | Specialization                                        | Operation speedup | Contributor(s)    |
1450|               |                    |                                                       | (up to)           |                   |
1451+===============+====================+=======================================================+===================+===================+
1452| Binary        | ``x + x``          | Binary add, multiply and subtract for common types    | 10%               | Mark Shannon,     |
1453| operations    |                    | such as :class:`int`, :class:`float` and :class:`str` |                   | Dong-hee Na,      |
1454|               | ``x - x``          | take custom fast paths for their underlying types.    |                   | Brandt Bucher,    |
1455|               |                    |                                                       |                   | Dennis Sweeney    |
1456|               | ``x * x``          |                                                       |                   |                   |
1457+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1458| Subscript     | ``a[i]``           | Subscripting container types such as :class:`list`,   | 10-25%            | Irit Katriel,     |
1459|               |                    | :class:`tuple` and :class:`dict` directly index       |                   | Mark Shannon      |
1460|               |                    | the underlying data structures.                       |                   |                   |
1461|               |                    |                                                       |                   |                   |
1462|               |                    | Subscripting custom :meth:`~object.__getitem__`       |                   |                   |
1463|               |                    | is also inlined similar to :ref:`inline-calls`.       |                   |                   |
1464+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1465| Store         | ``a[i] = z``       | Similar to subscripting specialization above.         | 10-25%            | Dennis Sweeney    |
1466| subscript     |                    |                                                       |                   |                   |
1467+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1468| Calls         | ``f(arg)``         | Calls to common builtin (C) functions and types such  | 20%               | Mark Shannon,     |
1469|               |                    | as :func:`len` and :class:`str` directly call their   |                   | Ken Jin           |
1470|               | ``C(arg)``         | underlying C version. This avoids going through the   |                   |                   |
1471|               |                    | internal calling convention.                          |                   |                   |
1472+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1473| Load          | ``print``          | The object's index in the globals/builtins namespace  | [#load-global]_   | Mark Shannon      |
1474| global        |                    | is cached. Loading globals and builtins require       |                   |                   |
1475| variable      | ``len``            | zero namespace lookups.                               |                   |                   |
1476+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1477| Load          | ``o.attr``         | Similar to loading global variables. The attribute's  | [#load-attr]_     | Mark Shannon      |
1478| attribute     |                    | index inside the class/object's namespace is cached.  |                   |                   |
1479|               |                    | In most cases, attribute loading will require zero    |                   |                   |
1480|               |                    | namespace lookups.                                    |                   |                   |
1481+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1482| Load          | ``o.meth()``       | The actual address of the method is cached. Method    | 10-20%            | Ken Jin,          |
1483| methods for   |                    | loading now has no namespace lookups -- even for      |                   | Mark Shannon      |
1484| call          |                    | classes with long inheritance chains.                 |                   |                   |
1485+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1486| Store         | ``o.attr = z``     | Similar to load attribute optimization.               | 2%                | Mark Shannon      |
1487| attribute     |                    |                                                       | in pyperformance  |                   |
1488+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1489| Unpack        | ``*seq``           | Specialized for common containers such as             | 8%                | Brandt Bucher     |
1490| Sequence      |                    | :class:`list` and :class:`tuple`.                     |                   |                   |
1491|               |                    | Avoids internal calling convention.                   |                   |                   |
1492+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+
1493
1494.. [#load-global] A similar optimization already existed since Python 3.8.
1495       3.11 specializes for more forms and reduces some overhead.
1496
1497.. [#load-attr] A similar optimization already existed since Python 3.10.
1498       3.11 specializes for more forms. Furthermore, all attribute loads should
1499       be sped up by :issue:`45947`.
1500
1501
1502.. _whatsnew311-faster-cpython-misc:
1503
1504Misc
1505----
1506
1507* Objects now require less memory due to lazily created object namespaces.
1508  Their namespace dictionaries now also share keys more freely.
1509  (Contributed Mark Shannon in :issue:`45340` and :issue:`40116`.)
1510
1511* "Zero-cost" exceptions are implemented, eliminating the cost
1512  of :keyword:`try` statements when no exception is raised.
1513  (Contributed by Mark Shannon in :issue:`40222`.)
1514
1515* A more concise representation of exceptions in the interpreter reduced the
1516  time required for catching an exception by about 10%.
1517  (Contributed by Irit Katriel in :issue:`45711`.)
1518
1519* :mod:`re`'s regular expression matching engine has been partially refactored,
1520  and now uses computed gotos (or "threaded code") on supported platforms. As a
1521  result, Python 3.11 executes the `pyperformance regular expression benchmarks
1522  <https://pyperformance.readthedocs.io/benchmarks.html#regex-dna>`_ up to 10%
1523  faster than Python 3.10.
1524  (Contributed by Brandt Bucher in :gh:`91404`.)
1525
1526
1527.. _whatsnew311-faster-cpython-faq:
1528
1529FAQ
1530---
1531
1532.. _faster-cpython-faq-my-code:
1533
1534How should I write my code to utilize these speedups?
1535^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1536
1537Write Pythonic code that follows common best practices;
1538you don't have to change your code.
1539The Faster CPython project optimizes for common code patterns we observe.
1540
1541
1542.. _faster-cpython-faq-memory:
1543
1544Will CPython 3.11 use more memory?
1545^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1546
1547Maybe not; we don't expect memory use to exceed 20% higher than 3.10.
1548This is offset by memory optimizations for frame objects and object
1549dictionaries as mentioned above.
1550
1551
1552.. _faster-cpython-ymmv:
1553
1554I don't see any speedups in my workload. Why?
1555^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1556
1557Certain code won't have noticeable benefits. If your code spends most of
1558its time on I/O operations, or already does most of its
1559computation in a C extension library like NumPy, there won't be significant
1560speedups. This project currently benefits pure-Python workloads the most.
1561
1562Furthermore, the pyperformance figures are a geometric mean. Even within the
1563pyperformance benchmarks, certain benchmarks have slowed down slightly, while
1564others have sped up by nearly 2x!
1565
1566
1567.. _faster-cpython-jit:
1568
1569Is there a JIT compiler?
1570^^^^^^^^^^^^^^^^^^^^^^^^
1571
1572No. We're still exploring other optimizations.
1573
1574
1575.. _whatsnew311-faster-cpython-about:
1576
1577About
1578-----
1579
1580Faster CPython explores optimizations for :term:`CPython`. The main team is
1581funded by Microsoft to work on this full-time. Pablo Galindo Salgado is also
1582funded by Bloomberg LP to work on the project part-time. Finally, many
1583contributors are volunteers from the community.
1584
1585
1586.. _whatsnew311-bytecode-changes:
1587
1588CPython bytecode changes
1589========================
1590
1591The bytecode now contains inline cache entries,
1592which take the form of the newly-added :opcode:`CACHE` instructions.
1593Many opcodes expect to be followed by an exact number of caches,
1594and instruct the interpreter to skip over them at runtime.
1595Populated caches can look like arbitrary instructions,
1596so great care should be taken when reading or modifying
1597raw, adaptive bytecode containing quickened data.
1598
1599
1600.. _whatsnew311-added-opcodes:
1601
1602New opcodes
1603-----------
1604
1605* :opcode:`ASYNC_GEN_WRAP`, :opcode:`RETURN_GENERATOR` and :opcode:`SEND`,
1606  used in generators and co-routines.
1607
1608* :opcode:`COPY_FREE_VARS`,
1609  which avoids needing special caller-side code for closures.
1610
1611* :opcode:`JUMP_BACKWARD_NO_INTERRUPT`,
1612  for use in certain loops where handling interrupts is undesirable.
1613
1614* :opcode:`MAKE_CELL`, to create :ref:`cell-objects`.
1615
1616* :opcode:`CHECK_EG_MATCH`  and  :opcode:`PREP_RERAISE_STAR`,
1617  to handle the :ref:`new exception groups and except* <whatsnew311-pep654>`
1618  added in :pep:`654`.
1619
1620* :opcode:`PUSH_EXC_INFO`, for use in exception handlers.
1621
1622* :opcode:`RESUME`, a no-op,
1623  for internal tracing, debugging and optimization checks.
1624
1625
1626.. _whatsnew311-replaced-opcodes:
1627
1628Replaced opcodes
1629----------------
1630
1631+------------------------------------+-----------------------------------+-----------------------------------------+
1632| Replaced Opcode(s)                 | New Opcode(s)                     | Notes                                   |
1633+====================================+===================================+=========================================+
1634| | :opcode:`!BINARY_*`              | :opcode:`BINARY_OP`               | Replaced all numeric binary/in-place    |
1635| | :opcode:`!INPLACE_*`             |                                   | opcodes with a single opcode            |
1636+------------------------------------+-----------------------------------+-----------------------------------------+
1637| | :opcode:`!CALL_FUNCTION`         | | :opcode:`CALL`                  | Decouples argument shifting for methods |
1638| | :opcode:`!CALL_FUNCTION_KW`      | | :opcode:`KW_NAMES`              | from handling of keyword arguments;     |
1639| | :opcode:`!CALL_METHOD`           | | :opcode:`PRECALL`               | allows better specialization of calls   |
1640|                                    | | :opcode:`PUSH_NULL`             |                                         |
1641+------------------------------------+-----------------------------------+-----------------------------------------+
1642| | :opcode:`!DUP_TOP`               | | :opcode:`COPY`                  | Stack manipulation instructions         |
1643| | :opcode:`!DUP_TOP_TWO`           | | :opcode:`SWAP`                  |                                         |
1644| | :opcode:`!ROT_TWO`               |                                   |                                         |
1645| | :opcode:`!ROT_THREE`             |                                   |                                         |
1646| | :opcode:`!ROT_FOUR`              |                                   |                                         |
1647| | :opcode:`!ROT_N`                 |                                   |                                         |
1648+------------------------------------+-----------------------------------+-----------------------------------------+
1649| | :opcode:`!JUMP_IF_NOT_EXC_MATCH` | | :opcode:`CHECK_EXC_MATCH`       | Now performs check but doesn't jump     |
1650+------------------------------------+-----------------------------------+-----------------------------------------+
1651| | :opcode:`!JUMP_ABSOLUTE`         | | :opcode:`JUMP_BACKWARD`         | See [#bytecode-jump]_;                  |
1652| | :opcode:`!POP_JUMP_IF_FALSE`     | | :opcode:`POP_JUMP_BACKWARD_IF_* | ``TRUE``, ``FALSE``,                    |
1653| | :opcode:`!POP_JUMP_IF_TRUE`      |   <POP_JUMP_BACKWARD_IF_TRUE>`    | ``NONE`` and ``NOT_NONE`` variants      |
1654|                                    | | :opcode:`POP_JUMP_FORWARD_IF_*  | for each direction                      |
1655|                                    |   <POP_JUMP_FORWARD_IF_TRUE>`     |                                         |
1656+------------------------------------+-----------------------------------+-----------------------------------------+
1657| | :opcode:`!SETUP_WITH`            | :opcode:`BEFORE_WITH`             | :keyword:`with` block setup             |
1658| | :opcode:`!SETUP_ASYNC_WITH`      |                                   |                                         |
1659+------------------------------------+-----------------------------------+-----------------------------------------+
1660
1661.. [#bytecode-jump] All jump opcodes are now relative, including the
1662   existing :opcode:`JUMP_IF_TRUE_OR_POP` and :opcode:`JUMP_IF_FALSE_OR_POP`.
1663   The argument is now an offset from the current instruction
1664   rather than an absolute location.
1665
1666
1667.. _whatsnew311-changed-opcodes:
1668.. _whatsnew311-removed-opcodes:
1669.. _whatsnew311-changed-removed-opcodes:
1670
1671Changed/removed opcodes
1672-----------------------
1673
1674* Changed :opcode:`MATCH_CLASS` and :opcode:`MATCH_KEYS`
1675  to no longer push an additional boolean value to indicate success/failure.
1676  Instead, ``None`` is pushed on failure
1677  in place of the tuple of extracted values.
1678
1679* Changed opcodes that work with exceptions to reflect them
1680  now being represented as one item on the stack instead of three
1681  (see :gh:`89874`).
1682
1683* Removed :opcode:`!COPY_DICT_WITHOUT_KEYS`, :opcode:`!GEN_START`,
1684  :opcode:`!POP_BLOCK`, :opcode:`!SETUP_FINALLY` and :opcode:`!YIELD_FROM`.
1685
1686
1687.. _whatsnew311-deprecated:
1688.. _whatsnew311-python-api-deprecated:
1689
1690Deprecated
1691==========
1692
1693This section lists Python APIs that have been deprecated in Python 3.11.
1694
1695Deprecated C APIs are :ref:`listed separately <whatsnew311-c-api-deprecated>`.
1696
1697
1698.. _whatsnew311-deprecated-language:
1699.. _whatsnew311-deprecated-builtins:
1700
1701Language/Builtins
1702-----------------
1703
1704* Chaining :class:`classmethod` descriptors (introduced in :issue:`19072`)
1705  is now deprecated.  It can no longer be used to wrap other descriptors
1706  such as :class:`property`.  The core design of this feature was flawed
1707  and caused a number of downstream problems.  To "pass-through" a
1708  :class:`classmethod`, consider using the :attr:`!__wrapped__` attribute
1709  that was added in Python 3.10.
1710  (Contributed by Raymond Hettinger in :gh:`89519`.)
1711
1712* Octal escapes in string and bytes literals with values larger than ``0o377``
1713  (255 in decimal) now produce a :exc:`DeprecationWarning`.
1714  In a future Python version, they will raise a :exc:`SyntaxWarning` and
1715  eventually a :exc:`SyntaxError`.
1716  (Contributed by Serhiy Storchaka in :gh:`81548`.)
1717
1718* The delegation of :func:`int` to :meth:`~object.__trunc__` is now deprecated.
1719  Calling ``int(a)`` when ``type(a)`` implements :meth:`!__trunc__` but not
1720  :meth:`~object.__int__` or :meth:`~object.__index__` now raises
1721  a :exc:`DeprecationWarning`.
1722  (Contributed by Zackery Spytz in :issue:`44977`.)
1723
1724
1725.. _whatsnew311-deprecated-modules:
1726
1727Modules
1728-------
1729
1730.. _whatsnew311-pep594:
1731
1732* :pep:`594` led to the deprecations of the following modules
1733  slated for removal in Python 3.13:
1734
1735  +---------------------+---------------------+---------------------+---------------------+---------------------+
1736  | :mod:`aifc`         | :mod:`chunk`        | :mod:`msilib`       | :mod:`pipes`        | :mod:`telnetlib`    |
1737  +---------------------+---------------------+---------------------+---------------------+---------------------+
1738  | :mod:`audioop`      | :mod:`crypt`        | :mod:`nis`          | :mod:`sndhdr`       | :mod:`uu`           |
1739  +---------------------+---------------------+---------------------+---------------------+---------------------+
1740  | :mod:`cgi`          | :mod:`imghdr`       | :mod:`nntplib`      | :mod:`spwd`         | :mod:`xdrlib`       |
1741  +---------------------+---------------------+---------------------+---------------------+---------------------+
1742  | :mod:`cgitb`        | :mod:`mailcap`      | :mod:`ossaudiodev`  | :mod:`sunau`        |                     |
1743  +---------------------+---------------------+---------------------+---------------------+---------------------+
1744
1745  (Contributed by Brett Cannon in :issue:`47061` and Victor Stinner in
1746  :gh:`68966`.)
1747
1748* The :mod:`asynchat`, :mod:`asyncore` and  :mod:`smtpd` modules have been
1749  deprecated since at least Python 3.6. Their documentation and deprecation
1750  warnings have now been updated to note they will be removed in Python 3.12.
1751  (Contributed by Hugo van Kemenade in :issue:`47022`.)
1752
1753* The :mod:`lib2to3` package and :ref:`2to3 <2to3-reference>` tool
1754  are now deprecated and may not be able to parse Python 3.10 or newer.
1755  See :pep:`617`, introducing the new PEG parser, for details.
1756  (Contributed by Victor Stinner in :issue:`40360`.)
1757
1758* Undocumented modules :mod:`!sre_compile`, :mod:`!sre_constants`
1759  and :mod:`!sre_parse` are now deprecated.
1760  (Contributed by Serhiy Storchaka in :issue:`47152`.)
1761
1762
1763.. _whatsnew311-deprecated-stdlib:
1764
1765Standard Library
1766----------------
1767
1768* The following have been deprecated in :mod:`configparser` since Python 3.2.
1769  Their deprecation warnings have now been updated to note they will be removed
1770  in Python 3.12:
1771
1772  * the :class:`!configparser.SafeConfigParser` class
1773  * the :attr:`!configparser.ParsingError.filename` property
1774  * the :meth:`configparser.RawConfigParser.readfp` method
1775
1776  (Contributed by Hugo van Kemenade in :issue:`45173`.)
1777
1778* :class:`!configparser.LegacyInterpolation` has been deprecated in the docstring
1779  since Python 3.2, and is not listed in the :mod:`configparser` documentation.
1780  It now emits a :exc:`DeprecationWarning` and will be removed
1781  in Python 3.13. Use :class:`configparser.BasicInterpolation` or
1782  :class:`configparser.ExtendedInterpolation` instead.
1783  (Contributed by Hugo van Kemenade in :issue:`46607`.)
1784
1785* The older set of :mod:`importlib.resources` functions were deprecated
1786  in favor of the replacements added in Python 3.9
1787  and will be removed in a future Python version,
1788  due to not supporting resources located within package subdirectories:
1789
1790  * :func:`importlib.resources.contents`
1791  * :func:`importlib.resources.is_resource`
1792  * :func:`importlib.resources.open_binary`
1793  * :func:`importlib.resources.open_text`
1794  * :func:`importlib.resources.read_binary`
1795  * :func:`importlib.resources.read_text`
1796  * :func:`importlib.resources.path`
1797
1798* The :func:`locale.getdefaultlocale` function is deprecated and will be
1799  removed in Python 3.13. Use :func:`locale.setlocale`,
1800  :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>` and
1801  :func:`locale.getlocale` functions instead.
1802  (Contributed by Victor Stinner in :gh:`90817`.)
1803
1804* The :func:`locale.resetlocale` function is deprecated and will be
1805  removed in Python 3.13. Use ``locale.setlocale(locale.LC_ALL, "")`` instead.
1806  (Contributed by Victor Stinner in :gh:`90817`.)
1807
1808* Stricter rules will now be applied for numerical group references
1809  and group names in :ref:`regular expressions <re-syntax>`.
1810  Only sequences of ASCII digits will now be accepted as a numerical reference,
1811  and the group name in :class:`bytes` patterns and replacement strings
1812  can only contain ASCII letters, digits and underscores.
1813  For now, a deprecation warning is raised for syntax violating these rules.
1814  (Contributed by Serhiy Storchaka in :gh:`91760`.)
1815
1816* In the :mod:`re` module, the :func:`!re.template` function
1817  and the corresponding :data:`!re.TEMPLATE` and :data:`!re.T` flags
1818  are deprecated, as they were undocumented and lacked an obvious purpose.
1819  They will be removed in Python 3.13.
1820  (Contributed by Serhiy Storchaka and Miro Hrončok in :gh:`92728`.)
1821
1822* :func:`turtle.settiltangle` has been deprecated since Python 3.1;
1823  it now emits a deprecation warning and will be removed in Python 3.13. Use
1824  :func:`turtle.tiltangle` instead (it was earlier incorrectly marked
1825  as deprecated, and its docstring is now corrected).
1826  (Contributed by Hugo van Kemenade in :issue:`45837`.)
1827
1828* :class:`typing.Text`, which exists solely to provide compatibility support
1829  between Python 2 and Python 3 code, is now deprecated. Its removal is
1830  currently unplanned, but users are encouraged to use :class:`str` instead
1831  wherever possible.
1832  (Contributed by Alex Waygood in :gh:`92332`.)
1833
1834* The keyword argument syntax for constructing :data:`typing.TypedDict` types
1835  is now deprecated. Support will be removed in Python 3.13. (Contributed by
1836  Jingchen Ye in :gh:`90224`.)
1837
1838* :class:`!webbrowser.MacOSX` is deprecated and will be removed in Python 3.13.
1839  It is untested, undocumented, and not used by :mod:`webbrowser` itself.
1840  (Contributed by Dong-hee Na in :issue:`42255`.)
1841
1842* The behavior of returning a value from a :class:`~unittest.TestCase` and
1843  :class:`~unittest.IsolatedAsyncioTestCase` test methods (other than the
1844  default ``None`` value) is now deprecated.
1845
1846* Deprecated the following not-formally-documented :mod:`unittest` functions,
1847  scheduled for removal in Python 3.13:
1848
1849  * :func:`!unittest.findTestCases`
1850  * :func:`!unittest.makeSuite`
1851  * :func:`!unittest.getTestCaseNames`
1852
1853  Use :class:`~unittest.TestLoader` methods instead:
1854
1855  * :meth:`unittest.TestLoader.loadTestsFromModule`
1856  * :meth:`unittest.TestLoader.loadTestsFromTestCase`
1857  * :meth:`unittest.TestLoader.getTestCaseNames`
1858
1859  (Contributed by Erlend E. Aasland in :issue:`5846`.)
1860
1861* :meth:`~!unittest.TestProgram.usageExit` is marked deprecated, to be removed
1862  in 3.13.
1863  (Contributed by Carlos Damázio in :gh:`67048`.)
1864
1865
1866.. _whatsnew311-pending-removal:
1867.. _whatsnew311-python-api-pending-removal:
1868
1869Pending Removal in Python 3.12
1870==============================
1871
1872The following Python APIs have been deprecated in earlier Python releases,
1873and will be removed in Python 3.12.
1874
1875C APIs pending removal are
1876:ref:`listed separately <whatsnew311-c-api-pending-removal>`.
1877
1878* The :mod:`asynchat` module
1879* The :mod:`asyncore` module
1880* The :ref:`entire distutils package <distutils-deprecated>`
1881* The :mod:`imp` module
1882* The :class:`typing.io <typing.IO>` namespace
1883* The :class:`typing.re <typing.Pattern>` namespace
1884* :func:`!cgi.log`
1885* :func:`importlib.find_loader`
1886* :meth:`importlib.abc.Loader.module_repr`
1887* :meth:`importlib.abc.MetaPathFinder.find_module`
1888* :meth:`importlib.abc.PathEntryFinder.find_loader`
1889* :meth:`importlib.abc.PathEntryFinder.find_module`
1890* :meth:`!importlib.machinery.BuiltinImporter.find_module`
1891* :meth:`!importlib.machinery.BuiltinLoader.module_repr`
1892* :meth:`!importlib.machinery.FileFinder.find_loader`
1893* :meth:`!importlib.machinery.FileFinder.find_module`
1894* :meth:`!importlib.machinery.FrozenImporter.find_module`
1895* :meth:`!importlib.machinery.FrozenLoader.module_repr`
1896* :meth:`importlib.machinery.PathFinder.find_module`
1897* :meth:`!importlib.machinery.WindowsRegistryFinder.find_module`
1898* :func:`importlib.util.module_for_loader`
1899* :func:`!importlib.util.set_loader_wrapper`
1900* :func:`!importlib.util.set_package_wrapper`
1901* :class:`pkgutil.ImpImporter`
1902* :class:`pkgutil.ImpLoader`
1903* :meth:`pathlib.Path.link_to`
1904* :func:`!sqlite3.enable_shared_cache`
1905* :func:`!sqlite3.OptimizedUnicode`
1906* :envvar:`PYTHONTHREADDEBUG` environment variable
1907* The following deprecated aliases in :mod:`unittest`:
1908
1909    ============================ =============================== ===============
1910       Deprecated alias           Method Name                     Deprecated in
1911    ============================ =============================== ===============
1912     ``failUnless``               :meth:`.assertTrue`             3.1
1913     ``failIf``                   :meth:`.assertFalse`            3.1
1914     ``failUnlessEqual``          :meth:`.assertEqual`            3.1
1915     ``failIfEqual``              :meth:`.assertNotEqual`         3.1
1916     ``failUnlessAlmostEqual``    :meth:`.assertAlmostEqual`      3.1
1917     ``failIfAlmostEqual``        :meth:`.assertNotAlmostEqual`   3.1
1918     ``failUnlessRaises``         :meth:`.assertRaises`           3.1
1919     ``assert_``                  :meth:`.assertTrue`             3.2
1920     ``assertEquals``             :meth:`.assertEqual`            3.2
1921     ``assertNotEquals``          :meth:`.assertNotEqual`         3.2
1922     ``assertAlmostEquals``       :meth:`.assertAlmostEqual`      3.2
1923     ``assertNotAlmostEquals``    :meth:`.assertNotAlmostEqual`   3.2
1924     ``assertRegexpMatches``      :meth:`.assertRegex`            3.2
1925     ``assertRaisesRegexp``       :meth:`.assertRaisesRegex`      3.2
1926     ``assertNotRegexpMatches``   :meth:`.assertNotRegex`         3.5
1927    ============================ =============================== ===============
1928
1929.. _whatsnew311-removed:
1930.. _whatsnew311-python-api-removed:
1931
1932Removed
1933=======
1934
1935This section lists Python APIs that have been removed in Python 3.11.
1936
1937Removed C APIs are :ref:`listed separately <whatsnew311-c-api-removed>`.
1938
1939* Removed the :func:`!@asyncio.coroutine` :term:`decorator`
1940  enabling legacy generator-based coroutines to be compatible with
1941  :keyword:`async` / :keyword:`await` code.
1942  The function has been deprecated since Python 3.8 and the removal was
1943  initially scheduled for Python 3.10. Use :keyword:`async def` instead.
1944  (Contributed by Illia Volochii in :issue:`43216`.)
1945
1946* Removed :class:`!asyncio.coroutines.CoroWrapper` used for wrapping legacy
1947  generator-based coroutine objects in the debug mode.
1948  (Contributed by Illia Volochii in :issue:`43216`.)
1949
1950* Due to significant security concerns, the *reuse_address* parameter of
1951  :meth:`asyncio.loop.create_datagram_endpoint`, disabled in Python 3.9, is
1952  now entirely removed. This is because of the behavior of the socket option
1953  ``SO_REUSEADDR`` in UDP.
1954  (Contributed by Hugo van Kemenade in :issue:`45129`.)
1955
1956* Removed the :mod:`!binhex` module, deprecated in Python 3.9.
1957  Also removed the related, similarly-deprecated :mod:`binascii` functions:
1958
1959  * :func:`!binascii.a2b_hqx`
1960  * :func:`!binascii.b2a_hqx`
1961  * :func:`!binascii.rlecode_hqx`
1962  * :func:`!binascii.rldecode_hqx`
1963
1964  The :func:`binascii.crc_hqx` function remains available.
1965
1966  (Contributed by Victor Stinner in :issue:`45085`.)
1967
1968* Removed the :mod:`distutils` ``bdist_msi`` command deprecated in Python 3.9.
1969  Use ``bdist_wheel`` (wheel packages) instead.
1970  (Contributed by Hugo van Kemenade in :issue:`45124`.)
1971
1972* Removed the :meth:`~object.__getitem__` methods of
1973  :class:`xml.dom.pulldom.DOMEventStream`, :class:`wsgiref.util.FileWrapper`
1974  and :class:`fileinput.FileInput`, deprecated since Python 3.9.
1975  (Contributed by Hugo van Kemenade in :issue:`45132`.)
1976
1977* Removed the deprecated :mod:`gettext` functions
1978  :func:`!lgettext`, :func:`!ldgettext`,
1979  :func:`!lngettext` and :func:`!ldngettext`.
1980  Also removed the :func:`!bind_textdomain_codeset` function,
1981  the :meth:`!NullTranslations.output_charset` and
1982  :meth:`!NullTranslations.set_output_charset` methods,
1983  and the *codeset* parameter of :func:`!translation` and :func:`!install`,
1984  since they are only used for the :func:`!l*gettext` functions.
1985  (Contributed by Dong-hee Na and Serhiy Storchaka in :issue:`44235`.)
1986
1987* Removed from the :mod:`inspect` module:
1988
1989  * The :func:`!getargspec` function, deprecated since Python 3.0;
1990    use :func:`inspect.signature` or :func:`inspect.getfullargspec` instead.
1991
1992  * The :func:`!formatargspec` function, deprecated since Python 3.5;
1993    use the :func:`inspect.signature` function
1994    or the :class:`inspect.Signature` object directly.
1995
1996  * The undocumented :meth:`!Signature.from_builtin`
1997    and :meth:`!Signature.from_function` methods, deprecated since Python 3.5;
1998    use the :meth:`Signature.from_callable() <inspect.Signature.from_callable>`
1999    method instead.
2000
2001  (Contributed by Hugo van Kemenade in :issue:`45320`.)
2002
2003* Removed the :meth:`~object.__class_getitem__` method
2004  from :class:`pathlib.PurePath`,
2005  because it was not used and added by mistake in previous versions.
2006  (Contributed by Nikita Sobolev in :issue:`46483`.)
2007
2008* Removed the :class:`!MailmanProxy` class in the :mod:`smtpd` module,
2009  as it is unusable without the external :mod:`!mailman` package.
2010  (Contributed by Dong-hee Na in :issue:`35800`.)
2011
2012* Removed the deprecated :meth:`!split` method of :class:`!_tkinter.TkappType`.
2013  (Contributed by Erlend E. Aasland in :issue:`38371`.)
2014
2015* Removed namespace package support from :mod:`unittest` discovery.
2016  It was introduced in Python 3.4 but has been broken since Python 3.7.
2017  (Contributed by Inada Naoki in :issue:`23882`.)
2018
2019* Removed the undocumented private :meth:`!float.__set_format__()` method,
2020  previously known as :meth:`!float.__setformat__()` in Python 3.7.
2021  Its docstring said: "You probably don't want to use this function.
2022  It exists mainly to be used in Python's test suite."
2023  (Contributed by Victor Stinner in :issue:`46852`.)
2024
2025* The :option:`!--experimental-isolated-subinterpreters` configure flag
2026  (and corresponding :c:macro:`!EXPERIMENTAL_ISOLATED_SUBINTERPRETERS` macro)
2027  have been removed.
2028
2029* `Pynche <https://pypi.org/project/pynche/>`_
2030  --- The Pythonically Natural Color and Hue Editor --- has been moved out
2031  of ``Tools/scripts`` and is `being developed independently
2032  <https://gitlab.com/warsaw/pynche/-/tree/main>`_ from the Python source tree.
2033
2034
2035.. _whatsnew311-porting:
2036.. _whatsnew311-python-api-porting:
2037
2038Porting to Python 3.11
2039======================
2040
2041This section lists previously described changes and other bugfixes
2042in the Python API that may require changes to your Python code.
2043
2044Porting notes for the C API are
2045:ref:`listed separately <whatsnew311-c-api-porting>`.
2046
2047* :func:`open`, :func:`io.open`, :func:`codecs.open` and
2048  :class:`fileinput.FileInput` no longer accept ``'U'`` ("universal newline")
2049  in the file mode. In Python 3, "universal newline" mode is used by default
2050  whenever a file is opened in text mode,
2051  and the ``'U'`` flag has been deprecated since Python 3.3.
2052  The :ref:`newline parameter <open-newline-parameter>`
2053  to these functions controls how universal newlines work.
2054  (Contributed by Victor Stinner in :issue:`37330`.)
2055
2056* :class:`ast.AST` node positions are now validated when provided to
2057  :func:`compile` and other related functions. If invalid positions are detected,
2058  a :exc:`ValueError` will be raised. (Contributed by Pablo Galindo in :gh:`93351`)
2059
2060* Prohibited passing non-:class:`concurrent.futures.ThreadPoolExecutor`
2061  executors to :meth:`asyncio.loop.set_default_executor`
2062  following a deprecation in Python 3.8.
2063  (Contributed by Illia Volochii in :issue:`43234`.)
2064
2065* :mod:`calendar`: The :class:`calendar.LocaleTextCalendar` and
2066  :class:`calendar.LocaleHTMLCalendar` classes now use
2067  :func:`locale.getlocale`, instead of using :func:`locale.getdefaultlocale`,
2068  if no locale is specified.
2069  (Contributed by Victor Stinner in :issue:`46659`.)
2070
2071* The :mod:`pdb` module now reads the :file:`.pdbrc` configuration file with
2072  the ``'UTF-8'`` encoding.
2073  (Contributed by Srinivas Reddy Thatiparthy (శ్రీనివాస్  రెడ్డి తాటిపర్తి) in :issue:`41137`.)
2074
2075* The *population* parameter of :func:`random.sample` must be a sequence,
2076  and automatic conversion of :class:`set`\s to :class:`list`\s
2077  is no longer supported. Also, if the sample size
2078  is larger than the population size, a :exc:`ValueError` is raised.
2079  (Contributed by Raymond Hettinger in :issue:`40465`.)
2080
2081* The *random* optional parameter of :func:`random.shuffle` was removed.
2082  It was previously an arbitrary random function to use for the shuffle;
2083  now, :func:`random.random` (its previous default) will always be used.
2084
2085* In :mod:`re` :ref:`re-syntax`, global inline flags (e.g. ``(?i)``)
2086  can now only be used at the start of regular expressions.
2087  Using them elsewhere has been deprecated since Python 3.6.
2088  (Contributed by Serhiy Storchaka in :issue:`47066`.)
2089
2090* In the :mod:`re` module, several long-standing bugs where fixed that,
2091  in rare cases, could cause capture groups to get the wrong result.
2092  Therefore, this could change the captured output in these cases.
2093  (Contributed by Ma Lin in :issue:`35859`.)
2094
2095
2096.. _whatsnew311-build-changes:
2097
2098Build Changes
2099=============
2100
2101* CPython now has :pep:`11` :pep:`Tier 3 support <11#tier-3>` for
2102  cross compiling to the `WebAssembly <https://webassembly.org/>`_ platforms
2103  `Emscripten <https://emscripten.org/>`_
2104  (``wasm32-unknown-emscripten``, i.e. Python in the browser)
2105  and `WebAssembly System Interface (WASI) <https://wasi.dev/>`_
2106  (``wasm32-unknown-wasi``).
2107  The effort is inspired by previous work like `Pyodide <https://pyodide.org/>`_.
2108  These platforms provide a limited subset of POSIX APIs; Python standard
2109  libraries features and modules related to networking, processes, threading,
2110  signals, mmap, and users/groups are not available or don't work.
2111  (Emscripten contributed by Christian Heimes and Ethan Smith in :gh:`84461`
2112  and WASI contributed by Christian Heimes in :gh:`90473`;
2113  platforms promoted in :gh:`95085`)
2114
2115* Building CPython now requires:
2116
2117  * A `C11 <https://en.cppreference.com/w/c/11>`_ compiler and standard library.
2118    `Optional C11 features
2119    <https://en.wikipedia.org/wiki/C11_(C_standard_revision)#Optional_features>`_
2120    are not required.
2121    (Contributed by Victor Stinner in :issue:`46656`,
2122    :issue:`45440` and :issue:`46640`.)
2123
2124  * Support for `IEEE 754 <https://en.wikipedia.org/wiki/IEEE_754>`_
2125    floating point numbers.
2126    (Contributed by Victor Stinner in :issue:`46917`.)
2127
2128* The :c:macro:`!Py_NO_NAN` macro has been removed.
2129  Since CPython now requires IEEE 754 floats, NaN values are always available.
2130  (Contributed by Victor Stinner in :issue:`46656`.)
2131
2132* The :mod:`tkinter` package now requires `Tcl/Tk <https://www.tcl.tk>`_
2133  version 8.5.12 or newer.
2134  (Contributed by Serhiy Storchaka in :issue:`46996`.)
2135
2136* Build dependencies, compiler flags, and linker flags for most stdlib
2137  extension modules are now detected by :program:`configure`. libffi, libnsl,
2138  libsqlite3, zlib, bzip2, liblzma, libcrypt, Tcl/Tk, and uuid flags
2139  are detected by `pkg-config
2140  <https://www.freedesktop.org/wiki/Software/pkg-config/>`_ (when available).
2141  :mod:`tkinter` now requires a pkg-config command
2142  to detect development settings for `Tcl/Tk`_ headers and libraries.
2143  (Contributed by Christian Heimes and Erlend Egeberg Aasland in
2144  :issue:`45847`, :issue:`45747`, and :issue:`45763`.)
2145
2146* libpython is no longer linked against libcrypt.
2147  (Contributed by Mike Gilbert in :issue:`45433`.)
2148
2149* CPython can now be built with the
2150  `ThinLTO <https://clang.llvm.org/docs/ThinLTO.html>`_ option
2151  via passing ``thin`` to :option:`--with-lto`, i.e. ``--with-lto=thin``.
2152  (Contributed by Dong-hee Na and Brett Holman in :issue:`44340`.)
2153
2154* Freelists for object structs can now be disabled. A new :program:`configure`
2155  option :option:`!--without-freelists` can be used to disable all freelists
2156  except empty tuple singleton.
2157  (Contributed by Christian Heimes in :issue:`45522`.)
2158
2159* ``Modules/Setup`` and ``Modules/makesetup`` have been improved and tied up.
2160  Extension modules can now be built through ``makesetup``. All except some
2161  test modules can be linked statically into a main binary or library.
2162  (Contributed by Brett Cannon and Christian Heimes in :issue:`45548`,
2163  :issue:`45570`, :issue:`45571`, and :issue:`43974`.)
2164
2165  .. note::
2166     Use the environment variables :envvar:`!TCLTK_CFLAGS` and
2167     :envvar:`!TCLTK_LIBS` to manually specify the location of Tcl/Tk headers
2168     and libraries. The :program:`configure` options
2169     :option:`!--with-tcltk-includes` and :option:`!--with-tcltk-libs`
2170     have been removed.
2171
2172     On RHEL 7 and CentOS 7 the development packages do not provide ``tcl.pc``
2173     and ``tk.pc``; use ``TCLTK_LIBS="-ltk8.5 -ltkstub8.5 -ltcl8.5"``.
2174     The directory ``Misc/rhel7`` contains ``.pc`` files and instructions
2175     on how to build Python with RHEL 7's and CentOS 7's Tcl/Tk and OpenSSL.
2176
2177* CPython will now use 30-bit digits by default for the Python :class:`int`
2178  implementation. Previously, the default was to use 30-bit digits on platforms
2179  with ``SIZEOF_VOID_P >= 8``, and 15-bit digits otherwise. It's still possible
2180  to explicitly request use of 15-bit digits via either the
2181  :option:`--enable-big-digits` option to the configure script
2182  or (for Windows) the ``PYLONG_BITS_IN_DIGIT`` variable in ``PC/pyconfig.h``,
2183  but this option may be removed at some point in the future.
2184  (Contributed by Mark Dickinson in :issue:`45569`.)
2185
2186
2187.. _whatsnew311-c-api:
2188
2189C API Changes
2190=============
2191
2192.. _whatsnew311-c-api-new-features:
2193
2194New Features
2195------------
2196
2197* Add a new :c:func:`PyType_GetName` function to get type's short name.
2198  (Contributed by Hai Shi in :issue:`42035`.)
2199
2200* Add a new :c:func:`PyType_GetQualName` function to get type's qualified name.
2201  (Contributed by Hai Shi in :issue:`42035`.)
2202
2203* Add new :c:func:`PyThreadState_EnterTracing` and
2204  :c:func:`PyThreadState_LeaveTracing` functions to the limited C API to
2205  suspend and resume tracing and profiling.
2206  (Contributed by Victor Stinner in :issue:`43760`.)
2207
2208* Added the :c:data:`Py_Version` constant which bears the same value as
2209  :c:macro:`PY_VERSION_HEX`.
2210  (Contributed by  Gabriele N. Tornetta in :issue:`43931`.)
2211
2212* :c:type:`Py_buffer` and APIs are now part of the limited API and the stable
2213  ABI:
2214
2215  * :c:func:`PyObject_CheckBuffer`
2216  * :c:func:`PyObject_GetBuffer`
2217  * :c:func:`PyBuffer_GetPointer`
2218  * :c:func:`PyBuffer_SizeFromFormat`
2219  * :c:func:`PyBuffer_ToContiguous`
2220  * :c:func:`PyBuffer_FromContiguous`
2221  * :c:func:`PyBuffer_CopyData`
2222  * :c:func:`PyBuffer_IsContiguous`
2223  * :c:func:`PyBuffer_FillContiguousStrides`
2224  * :c:func:`PyBuffer_FillInfo`
2225  * :c:func:`PyBuffer_Release`
2226  * :c:func:`PyMemoryView_FromBuffer`
2227  * :c:member:`~PyBufferProcs.bf_getbuffer` and
2228    :c:member:`~PyBufferProcs.bf_releasebuffer` type slots
2229
2230  (Contributed by Christian Heimes in :issue:`45459`.)
2231
2232* Added the :c:data:`PyType_GetModuleByDef` function, used to get the module
2233  in which a method was defined, in cases where this information is not
2234  available directly (via :c:type:`PyCMethod`).
2235  (Contributed by Petr Viktorin in :issue:`46613`.)
2236
2237* Add new functions to pack and unpack C double (serialize and deserialize):
2238  :c:func:`PyFloat_Pack2`, :c:func:`PyFloat_Pack4`, :c:func:`PyFloat_Pack8`,
2239  :c:func:`PyFloat_Unpack2`, :c:func:`PyFloat_Unpack4` and
2240  :c:func:`PyFloat_Unpack8`.
2241  (Contributed by Victor Stinner in :issue:`46906`.)
2242
2243* Add new functions to get frame object attributes:
2244  :c:func:`PyFrame_GetBuiltins`, :c:func:`PyFrame_GetGenerator`,
2245  :c:func:`PyFrame_GetGlobals`, :c:func:`PyFrame_GetLasti`.
2246
2247* Added two new functions to get and set the active exception instance:
2248  :c:func:`PyErr_GetHandledException` and :c:func:`PyErr_SetHandledException`.
2249  These are alternatives to :c:func:`PyErr_SetExcInfo()` and
2250  :c:func:`PyErr_GetExcInfo()` which work with the legacy 3-tuple
2251  representation of exceptions.
2252  (Contributed by Irit Katriel in :issue:`46343`.)
2253
2254* Added the :c:member:`PyConfig.safe_path` member.
2255  (Contributed by Victor Stinner in :gh:`57684`.)
2256
2257
2258.. _whatsnew311-c-api-porting:
2259
2260Porting to Python 3.11
2261----------------------
2262
2263.. _whatsnew311-pep670:
2264
2265* Some macros have been converted to static inline functions to avoid
2266  `macro pitfalls <https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html>`_.
2267  The change should be mostly transparent to users,
2268  as the replacement functions will cast their arguments to the expected types
2269  to avoid compiler warnings due to static type checks.
2270  However, when the limited C API is set to >=3.11,
2271  these casts are not done,
2272  and callers will need to cast arguments to their expected types.
2273  See :pep:`670` for more details.
2274  (Contributed by Victor Stinner and Erlend E. Aasland in :gh:`89653`.)
2275
2276* :c:func:`PyErr_SetExcInfo()` no longer uses the ``type`` and ``traceback``
2277  arguments, the interpreter now derives those values from the exception
2278  instance (the ``value`` argument). The function still steals references
2279  of all three arguments.
2280  (Contributed by Irit Katriel in :issue:`45711`.)
2281
2282* :c:func:`PyErr_GetExcInfo()` now derives the ``type`` and ``traceback``
2283  fields of the result from the exception instance (the ``value`` field).
2284  (Contributed by Irit Katriel in :issue:`45711`.)
2285
2286* :c:struct:`_frozen` has a new ``is_package`` field to indicate whether
2287  or not the frozen module is a package.  Previously, a negative value
2288  in the ``size`` field was the indicator.  Now only non-negative values
2289  be used for ``size``.
2290  (Contributed by Kumar Aditya in :issue:`46608`.)
2291
2292* :c:func:`_PyFrameEvalFunction` now takes ``_PyInterpreterFrame*``
2293  as its second parameter, instead of ``PyFrameObject*``.
2294  See :pep:`523` for more details of how to use this function pointer type.
2295
2296* :c:func:`PyCode_New` and :c:func:`PyCode_NewWithPosOnlyArgs` now take
2297  an additional ``exception_table`` argument.
2298  Using these functions should be avoided, if at all possible.
2299  To get a custom code object: create a code object using the compiler,
2300  then get a modified version with the ``replace`` method.
2301
2302* :c:type:`PyCodeObject` no longer has the ``co_code``, ``co_varnames``,
2303  ``co_cellvars`` and ``co_freevars`` fields.  Instead, use
2304  :c:func:`PyCode_GetCode`, :c:func:`PyCode_GetVarnames`,
2305  :c:func:`PyCode_GetCellvars` and :c:func:`PyCode_GetFreevars` respectively
2306  to access them via the C API.
2307  (Contributed by Brandt Bucher in :issue:`46841` and Ken Jin in :gh:`92154`
2308  and :gh:`94936`.)
2309
2310* The old trashcan macros (``Py_TRASHCAN_SAFE_BEGIN``/``Py_TRASHCAN_SAFE_END``)
2311  are now deprecated. They should be replaced by the new macros
2312  ``Py_TRASHCAN_BEGIN`` and ``Py_TRASHCAN_END``.
2313
2314  A tp_dealloc function that has the old macros, such as::
2315
2316    static void
2317    mytype_dealloc(mytype *p)
2318    {
2319        PyObject_GC_UnTrack(p);
2320        Py_TRASHCAN_SAFE_BEGIN(p);
2321        ...
2322        Py_TRASHCAN_SAFE_END
2323    }
2324
2325  should migrate to the new macros as follows::
2326
2327    static void
2328    mytype_dealloc(mytype *p)
2329    {
2330        PyObject_GC_UnTrack(p);
2331        Py_TRASHCAN_BEGIN(p, mytype_dealloc)
2332        ...
2333        Py_TRASHCAN_END
2334    }
2335
2336  Note that ``Py_TRASHCAN_BEGIN`` has a second argument which
2337  should be the deallocation function it is in.
2338
2339  To support older Python versions in the same codebase, you
2340  can define the following macros and use them throughout
2341  the code (credit: these were copied from the ``mypy`` codebase)::
2342
2343    #if PY_VERSION_HEX >= 0x03080000
2344    #  define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc)
2345    #  define CPy_TRASHCAN_END(op) Py_TRASHCAN_END
2346    #else
2347    #  define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op)
2348    #  define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op)
2349    #endif
2350
2351* The :c:func:`PyType_Ready` function now raises an error if a type is defined
2352  with the :const:`Py_TPFLAGS_HAVE_GC` flag set but has no traverse function
2353  (:c:member:`PyTypeObject.tp_traverse`).
2354  (Contributed by Victor Stinner in :issue:`44263`.)
2355
2356* Heap types with the :const:`Py_TPFLAGS_IMMUTABLETYPE` flag can now inherit
2357  the :pep:`590` vectorcall protocol.  Previously, this was only possible for
2358  :ref:`static types <static-types>`.
2359  (Contributed by Erlend E. Aasland in :issue:`43908`)
2360
2361* Since :c:func:`Py_TYPE()` is changed to a inline static function,
2362  ``Py_TYPE(obj) = new_type`` must be replaced with
2363  ``Py_SET_TYPE(obj, new_type)``: see the :c:func:`Py_SET_TYPE()` function
2364  (available since Python 3.9). For backward compatibility, this macro can be
2365  used::
2366
2367      #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)
2368      static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)
2369      { ob->ob_type = type; }
2370      #define Py_SET_TYPE(ob, type) _Py_SET_TYPE((PyObject*)(ob), type)
2371      #endif
2372
2373  (Contributed by Victor Stinner in :issue:`39573`.)
2374
2375* Since :c:func:`Py_SIZE()` is changed to a inline static function,
2376  ``Py_SIZE(obj) = new_size`` must be replaced with
2377  ``Py_SET_SIZE(obj, new_size)``: see the :c:func:`Py_SET_SIZE()` function
2378  (available since Python 3.9). For backward compatibility, this macro can be
2379  used::
2380
2381      #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)
2382      static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)
2383      { ob->ob_size = size; }
2384      #define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)
2385      #endif
2386
2387  (Contributed by Victor Stinner in :issue:`39573`.)
2388
2389* ``<Python.h>`` no longer includes the header files ``<stdlib.h>``,
2390  ``<stdio.h>``, ``<errno.h>`` and ``<string.h>`` when the ``Py_LIMITED_API``
2391  macro is set to ``0x030b0000`` (Python 3.11) or higher. C extensions should
2392  explicitly include the header files after ``#include <Python.h>``.
2393  (Contributed by Victor Stinner in :issue:`45434`.)
2394
2395* The non-limited API files ``cellobject.h``, ``classobject.h``, ``code.h``, ``context.h``,
2396  ``funcobject.h``, ``genobject.h`` and ``longintrepr.h`` have been moved to
2397  the ``Include/cpython`` directory. Moreover, the ``eval.h`` header file was
2398  removed. These files must not be included directly, as they are already
2399  included in ``Python.h``: :ref:`Include Files <api-includes>`. If they have
2400  been included directly, consider including ``Python.h`` instead.
2401  (Contributed by Victor Stinner in :issue:`35134`.)
2402
2403* The :c:func:`PyUnicode_CHECK_INTERNED` macro has been excluded from the
2404  limited C API. It was never usable there, because it used internal structures
2405  which are not available in the limited C API.
2406  (Contributed by Victor Stinner in :issue:`46007`.)
2407
2408* The following frame functions and type are now directly available with
2409  ``#include <Python.h>``, it's no longer needed to add
2410  ``#include <frameobject.h>``:
2411
2412  * :c:func:`PyFrame_Check`
2413  * :c:func:`PyFrame_GetBack`
2414  * :c:func:`PyFrame_GetBuiltins`
2415  * :c:func:`PyFrame_GetGenerator`
2416  * :c:func:`PyFrame_GetGlobals`
2417  * :c:func:`PyFrame_GetLasti`
2418  * :c:func:`PyFrame_GetLocals`
2419  * :c:type:`PyFrame_Type`
2420
2421  (Contributed by Victor Stinner in :gh:`93937`.)
2422
2423.. _pyframeobject-3.11-hiding:
2424
2425* The :c:type:`PyFrameObject` structure members have been removed from the
2426  public C API.
2427
2428  While the documentation notes that the :c:type:`PyFrameObject` fields are
2429  subject to change at any time, they have been stable for a long time and were
2430  used in several popular extensions.
2431
2432  In Python 3.11, the frame struct was reorganized to allow performance
2433  optimizations. Some fields were removed entirely, as they were details of the
2434  old implementation.
2435
2436  :c:type:`PyFrameObject` fields:
2437
2438  * ``f_back``: use :c:func:`PyFrame_GetBack`.
2439  * ``f_blockstack``: removed.
2440  * ``f_builtins``: use :c:func:`PyFrame_GetBuiltins`.
2441  * ``f_code``: use :c:func:`PyFrame_GetCode`.
2442  * ``f_gen``: use :c:func:`PyFrame_GetGenerator`.
2443  * ``f_globals``: use :c:func:`PyFrame_GetGlobals`.
2444  * ``f_iblock``: removed.
2445  * ``f_lasti``: use :c:func:`PyFrame_GetLasti`.
2446    Code using ``f_lasti`` with ``PyCode_Addr2Line()`` should use
2447    :c:func:`PyFrame_GetLineNumber` instead; it may be faster.
2448  * ``f_lineno``: use :c:func:`PyFrame_GetLineNumber`
2449  * ``f_locals``: use :c:func:`PyFrame_GetLocals`.
2450  * ``f_stackdepth``: removed.
2451  * ``f_state``: no public API (renamed to ``f_frame.f_state``).
2452  * ``f_trace``: no public API.
2453  * ``f_trace_lines``: use ``PyObject_GetAttrString((PyObject*)frame, "f_trace_lines")``.
2454  * ``f_trace_opcodes``: use ``PyObject_GetAttrString((PyObject*)frame, "f_trace_opcodes")``.
2455  * ``f_localsplus``: no public API (renamed to ``f_frame.localsplus``).
2456  * ``f_valuestack``: removed.
2457
2458  The Python frame object is now created lazily. A side effect is that the
2459  ``f_back`` member must not be accessed directly, since its value is now also
2460  computed lazily. The :c:func:`PyFrame_GetBack` function must be called
2461  instead.
2462
2463  Debuggers that accessed the ``f_locals`` directly *must* call
2464  :c:func:`PyFrame_GetLocals` instead. They no longer need to call
2465  :c:func:`PyFrame_FastToLocalsWithError` or :c:func:`PyFrame_LocalsToFast`,
2466  in fact they should not call those functions. The necessary updating of the
2467  frame is now managed by the virtual machine.
2468
2469  Code defining ``PyFrame_GetCode()`` on Python 3.8 and older::
2470
2471      #if PY_VERSION_HEX < 0x030900B1
2472      static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)
2473      {
2474          Py_INCREF(frame->f_code);
2475          return frame->f_code;
2476      }
2477      #endif
2478
2479  Code defining ``PyFrame_GetBack()`` on Python 3.8 and older::
2480
2481      #if PY_VERSION_HEX < 0x030900B1
2482      static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)
2483      {
2484          Py_XINCREF(frame->f_back);
2485          return frame->f_back;
2486      }
2487      #endif
2488
2489  Or use the `pythoncapi_compat project
2490  <https://github.com/python/pythoncapi-compat>`__ to get these two
2491  functions on older Python versions.
2492
2493* Changes of the :c:type:`PyThreadState` structure members:
2494
2495  * ``frame``: removed, use :c:func:`PyThreadState_GetFrame` (function added
2496    to Python 3.9 by :issue:`40429`).
2497    Warning: the function returns a :term:`strong reference`, need to call
2498    :c:func:`Py_XDECREF`.
2499  * ``tracing``: changed, use :c:func:`PyThreadState_EnterTracing`
2500    and :c:func:`PyThreadState_LeaveTracing`
2501    (functions added to Python 3.11 by :issue:`43760`).
2502  * ``recursion_depth``: removed,
2503    use ``(tstate->recursion_limit - tstate->recursion_remaining)`` instead.
2504  * ``stackcheck_counter``: removed.
2505
2506  Code defining ``PyThreadState_GetFrame()`` on Python 3.8 and older::
2507
2508      #if PY_VERSION_HEX < 0x030900B1
2509      static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
2510      {
2511          Py_XINCREF(tstate->frame);
2512          return tstate->frame;
2513      }
2514      #endif
2515
2516  Code defining ``PyThreadState_EnterTracing()`` and
2517  ``PyThreadState_LeaveTracing()`` on Python 3.10 and older::
2518
2519      #if PY_VERSION_HEX < 0x030B00A2
2520      static inline void PyThreadState_EnterTracing(PyThreadState *tstate)
2521      {
2522          tstate->tracing++;
2523      #if PY_VERSION_HEX >= 0x030A00A1
2524          tstate->cframe->use_tracing = 0;
2525      #else
2526          tstate->use_tracing = 0;
2527      #endif
2528      }
2529
2530      static inline void PyThreadState_LeaveTracing(PyThreadState *tstate)
2531      {
2532          int use_tracing = (tstate->c_tracefunc != NULL || tstate->c_profilefunc != NULL);
2533          tstate->tracing--;
2534      #if PY_VERSION_HEX >= 0x030A00A1
2535          tstate->cframe->use_tracing = use_tracing;
2536      #else
2537          tstate->use_tracing = use_tracing;
2538      #endif
2539      }
2540      #endif
2541
2542  Or use `the pythoncapi-compat project
2543  <https://github.com/python/pythoncapi-compat>`__ to get these functions
2544  on old Python functions.
2545
2546* Distributors are encouraged to build Python with the optimized Blake2
2547  library `libb2`_.
2548
2549* The :c:member:`PyConfig.module_search_paths_set` field must now be set to 1 for
2550  initialization to use :c:member:`PyConfig.module_search_paths` to initialize
2551  :data:`sys.path`. Otherwise, initialization will recalculate the path and replace
2552  any values added to ``module_search_paths``.
2553
2554* :c:func:`PyConfig_Read` no longer calculates the initial search path, and will not
2555  fill any values into :c:member:`PyConfig.module_search_paths`. To calculate default
2556  paths and then modify them, finish initialization and use :c:func:`PySys_GetObject`
2557  to retrieve :data:`sys.path` as a Python list object and modify it directly.
2558
2559
2560.. _whatsnew311-c-api-deprecated:
2561
2562Deprecated
2563----------
2564
2565* Deprecate the following functions to configure the Python initialization:
2566
2567  * :c:func:`PySys_AddWarnOptionUnicode`
2568  * :c:func:`PySys_AddWarnOption`
2569  * :c:func:`PySys_AddXOption`
2570  * :c:func:`PySys_HasWarnOptions`
2571  * :c:func:`PySys_SetArgvEx`
2572  * :c:func:`PySys_SetArgv`
2573  * :c:func:`PySys_SetPath`
2574  * :c:func:`Py_SetPath`
2575  * :c:func:`Py_SetProgramName`
2576  * :c:func:`Py_SetPythonHome`
2577  * :c:func:`Py_SetStandardStreamEncoding`
2578  * :c:func:`_Py_SetProgramFullPath`
2579
2580  Use the new :c:type:`PyConfig` API of the :ref:`Python Initialization Configuration
2581  <init-config>` instead (:pep:`587`).
2582  (Contributed by Victor Stinner in :gh:`88279`.)
2583
2584* Deprecate the ``ob_shash`` member of the :c:type:`PyBytesObject`. Use :c:func:`PyObject_Hash` instead.
2585  (Contributed by Inada Naoki in :issue:`46864`.)
2586
2587
2588.. _whatsnew311-c-api-pending-removal:
2589
2590Pending Removal in Python 3.12
2591------------------------------
2592
2593The following C APIs have been deprecated in earlier Python releases,
2594and will be removed in Python 3.12.
2595
2596* :c:func:`PyUnicode_AS_DATA`
2597* :c:func:`PyUnicode_AS_UNICODE`
2598* :c:func:`PyUnicode_AsUnicodeAndSize`
2599* :c:func:`PyUnicode_AsUnicode`
2600* :c:func:`PyUnicode_FromUnicode`
2601* :c:func:`PyUnicode_GET_DATA_SIZE`
2602* :c:func:`PyUnicode_GET_SIZE`
2603* :c:func:`PyUnicode_GetSize`
2604* :c:func:`PyUnicode_IS_COMPACT`
2605* :c:func:`PyUnicode_IS_READY`
2606* :c:func:`PyUnicode_READY`
2607* :c:func:`Py_UNICODE_WSTR_LENGTH`
2608* :c:func:`_PyUnicode_AsUnicode`
2609* :c:macro:`PyUnicode_WCHAR_KIND`
2610* :c:type:`PyUnicodeObject`
2611* :c:func:`PyUnicode_InternImmortal()`
2612
2613
2614.. _whatsnew311-c-api-removed:
2615
2616Removed
2617-------
2618
2619* :c:func:`PyFrame_BlockSetup` and :c:func:`PyFrame_BlockPop` have been
2620  removed.
2621  (Contributed by Mark Shannon in :issue:`40222`.)
2622
2623* Remove the following math macros using the ``errno`` variable:
2624
2625  * ``Py_ADJUST_ERANGE1()``
2626  * ``Py_ADJUST_ERANGE2()``
2627  * ``Py_OVERFLOWED()``
2628  * ``Py_SET_ERANGE_IF_OVERFLOW()``
2629  * ``Py_SET_ERRNO_ON_MATH_ERROR()``
2630
2631  (Contributed by Victor Stinner in :issue:`45412`.)
2632
2633* Remove ``Py_UNICODE_COPY()`` and ``Py_UNICODE_FILL()`` macros, deprecated
2634  since Python 3.3. Use ``PyUnicode_CopyCharacters()`` or ``memcpy()``
2635  (``wchar_t*`` string), and ``PyUnicode_Fill()`` functions instead.
2636  (Contributed by Victor Stinner in :issue:`41123`.)
2637
2638* Remove the ``pystrhex.h`` header file. It only contains private functions.
2639  C extensions should only include the main ``<Python.h>`` header file.
2640  (Contributed by Victor Stinner in :issue:`45434`.)
2641
2642* Remove the ``Py_FORCE_DOUBLE()`` macro. It was used by the
2643  ``Py_IS_INFINITY()`` macro.
2644  (Contributed by Victor Stinner in :issue:`45440`.)
2645
2646* The following items are no longer available when :c:macro:`Py_LIMITED_API`
2647  is defined:
2648
2649  * :c:func:`PyMarshal_WriteLongToFile`
2650  * :c:func:`PyMarshal_WriteObjectToFile`
2651  * :c:func:`PyMarshal_ReadObjectFromString`
2652  * :c:func:`PyMarshal_WriteObjectToString`
2653  * the ``Py_MARSHAL_VERSION`` macro
2654
2655  These are not part of the :ref:`limited API <stable-abi-list>`.
2656
2657  (Contributed by Victor Stinner in :issue:`45474`.)
2658
2659* Exclude :c:func:`PyWeakref_GET_OBJECT` from the limited C API. It never
2660  worked since the :c:type:`PyWeakReference` structure is opaque in the
2661  limited C API.
2662  (Contributed by Victor Stinner in :issue:`35134`.)
2663
2664* Remove the ``PyHeapType_GET_MEMBERS()`` macro. It was exposed in the
2665  public C API by mistake, it must only be used by Python internally.
2666  Use the ``PyTypeObject.tp_members`` member instead.
2667  (Contributed by Victor Stinner in :issue:`40170`.)
2668
2669* Remove the ``HAVE_PY_SET_53BIT_PRECISION`` macro (moved to the internal C
2670  API).
2671  (Contributed by Victor Stinner in :issue:`45412`.)
2672
2673.. _whatsnew311-pep624:
2674
2675* Remove the :c:type:`Py_UNICODE` encoder APIs,
2676  as they have been deprecated since Python 3.3,
2677  are little used
2678  and are inefficient relative to the recommended alternatives.
2679
2680  The removed functions are:
2681
2682  * :func:`!PyUnicode_Encode`
2683  * :func:`!PyUnicode_EncodeASCII`
2684  * :func:`!PyUnicode_EncodeLatin1`
2685  * :func:`!PyUnicode_EncodeUTF7`
2686  * :func:`!PyUnicode_EncodeUTF8`
2687  * :func:`!PyUnicode_EncodeUTF16`
2688  * :func:`!PyUnicode_EncodeUTF32`
2689  * :func:`!PyUnicode_EncodeUnicodeEscape`
2690  * :func:`!PyUnicode_EncodeRawUnicodeEscape`
2691  * :func:`!PyUnicode_EncodeCharmap`
2692  * :func:`!PyUnicode_TranslateCharmap`
2693  * :func:`!PyUnicode_EncodeDecimal`
2694  * :func:`!PyUnicode_TransformDecimalToASCII`
2695
2696  See :pep:`624` for details and
2697  :pep:`migration guidance <624#alternative-apis>`.
2698  (Contributed by Inada Naoki in :issue:`44029`.)
2699
2700
2701Notable Changes in 3.11.4
2702=========================
2703
2704tarfile
2705-------
2706
2707* The extraction methods in :mod:`tarfile`, and :func:`shutil.unpack_archive`,
2708  have a new a *filter* argument that allows limiting tar features than may be
2709  surprising or dangerous, such as creating files outside the destination
2710  directory.
2711  See :ref:`tarfile-extraction-filter` for details.
2712  In Python 3.12, use without the *filter* argument will show a
2713  :exc:`DeprecationWarning`.
2714  In Python 3.14, the default will switch to ``'data'``.
2715  (Contributed by Petr Viktorin in :pep:`706`.)
2716
2717.. _libb2: https://www.blake2.net/
2718