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/python-dev@python.org/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* As of 3.11.10, :func:`os.mkdir` and :func:`os.makedirs` on Windows 901 now support passing a *mode* value of ``0o700`` to apply access 902 control to the new directory. This implicitly affects 903 :func:`tempfile.mkdtemp` and is a mitigation for CVE-2024-4030. 904 Other values for *mode* continue to be ignored. 905 (Contributed by Steve Dower in :gh:`118486`.) 906 907 908.. _whatsnew311-pathlib: 909 910pathlib 911------- 912 913* :meth:`~pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` return only 914 directories if *pattern* ends with a pathname components separator: 915 :data:`~os.sep` or :data:`~os.altsep`. 916 (Contributed by Eisuke Kawasima in :issue:`22276` and :issue:`33392`.) 917 918 919.. _whatsnew311-re: 920 921re 922-- 923 924* Atomic grouping (``(?>...)``) and possessive quantifiers (``*+``, ``++``, 925 ``?+``, ``{m,n}+``) are now supported in regular expressions. 926 (Contributed by Jeffrey C. Jacobs and Serhiy Storchaka in :issue:`433030`.) 927 928 929.. _whatsnew311-shutil: 930 931shutil 932------ 933 934* Add optional parameter *dir_fd* in :func:`shutil.rmtree`. 935 (Contributed by Serhiy Storchaka in :issue:`46245`.) 936 937 938.. _whatsnew311-socket: 939 940socket 941------ 942 943* Add CAN Socket support for NetBSD. 944 (Contributed by Thomas Klausner in :issue:`30512`.) 945 946* :meth:`~socket.create_connection` has an option to raise, in case of 947 failure to connect, an :exc:`ExceptionGroup` containing all errors 948 instead of only raising the last error. 949 (Contributed by Irit Katriel in :issue:`29980`.) 950 951 952.. _whatsnew311-sqlite3: 953 954sqlite3 955------- 956 957* You can now disable the authorizer by passing :const:`None` to 958 :meth:`~sqlite3.Connection.set_authorizer`. 959 (Contributed by Erlend E. Aasland in :issue:`44491`.) 960 961* Collation name :meth:`~sqlite3.Connection.create_collation` can now 962 contain any Unicode character. Collation names with invalid characters 963 now raise :exc:`UnicodeEncodeError` instead of :exc:`sqlite3.ProgrammingError`. 964 (Contributed by Erlend E. Aasland in :issue:`44688`.) 965 966* :mod:`sqlite3` exceptions now include the SQLite extended error code as 967 :attr:`~sqlite3.Error.sqlite_errorcode` and the SQLite error name as 968 :attr:`~sqlite3.Error.sqlite_errorname`. 969 (Contributed by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland in 970 :issue:`16379` and :issue:`24139`.) 971 972* Add :meth:`~sqlite3.Connection.setlimit` and 973 :meth:`~sqlite3.Connection.getlimit` to :class:`sqlite3.Connection` for 974 setting and getting SQLite limits by connection basis. 975 (Contributed by Erlend E. Aasland in :issue:`45243`.) 976 977* :mod:`sqlite3` now sets :attr:`sqlite3.threadsafety` based on the default 978 threading mode the underlying SQLite library has been compiled with. 979 (Contributed by Erlend E. Aasland in :issue:`45613`.) 980 981* :mod:`sqlite3` C callbacks now use unraisable exceptions if callback 982 tracebacks are enabled. Users can now register an 983 :func:`unraisable hook handler <sys.unraisablehook>` to improve their debug 984 experience. 985 (Contributed by Erlend E. Aasland in :issue:`45828`.) 986 987* Fetch across rollback no longer raises :exc:`~sqlite3.InterfaceError`. 988 Instead we leave it to the SQLite library to handle these cases. 989 (Contributed by Erlend E. Aasland in :issue:`44092`.) 990 991* Add :meth:`~sqlite3.Connection.serialize` and 992 :meth:`~sqlite3.Connection.deserialize` to :class:`sqlite3.Connection` for 993 serializing and deserializing databases. 994 (Contributed by Erlend E. Aasland in :issue:`41930`.) 995 996* Add :meth:`~sqlite3.Connection.create_window_function` to 997 :class:`sqlite3.Connection` for creating aggregate window functions. 998 (Contributed by Erlend E. Aasland in :issue:`34916`.) 999 1000* Add :meth:`~sqlite3.Connection.blobopen` to :class:`sqlite3.Connection`. 1001 :class:`sqlite3.Blob` allows incremental I/O operations on blobs. 1002 (Contributed by Aviv Palivoda and Erlend E. Aasland in :issue:`24905`.) 1003 1004 1005.. _whatsnew311-string: 1006 1007string 1008------ 1009 1010* Add :meth:`~string.Template.get_identifiers` 1011 and :meth:`~string.Template.is_valid` to :class:`string.Template`, 1012 which respectively return all valid placeholders, 1013 and whether any invalid placeholders are present. 1014 (Contributed by Ben Kehoe in :gh:`90465`.) 1015 1016 1017.. _whatsnew311-sys: 1018 1019sys 1020--- 1021 1022* :func:`sys.exc_info` now derives the ``type`` and ``traceback`` fields 1023 from the ``value`` (the exception instance), so when an exception is 1024 modified while it is being handled, the changes are reflected in 1025 the results of subsequent calls to :func:`!exc_info`. 1026 (Contributed by Irit Katriel in :issue:`45711`.) 1027 1028* Add :func:`sys.exception` which returns the active exception instance 1029 (equivalent to ``sys.exc_info()[1]``). 1030 (Contributed by Irit Katriel in :issue:`46328`.) 1031 1032* Add the :data:`sys.flags.safe_path <sys.flags>` flag. 1033 (Contributed by Victor Stinner in :gh:`57684`.) 1034 1035 1036.. _whatsnew311-sysconfig: 1037 1038sysconfig 1039--------- 1040 1041* Three new :ref:`installation schemes <installation_paths>` 1042 (*posix_venv*, *nt_venv* and *venv*) were added and are used when Python 1043 creates new virtual environments or when it is running from a virtual 1044 environment. 1045 The first two schemes (*posix_venv* and *nt_venv*) are OS-specific 1046 for non-Windows and Windows, the *venv* is essentially an alias to one of 1047 them according to the OS Python runs on. 1048 This is useful for downstream distributors who modify 1049 :func:`sysconfig.get_preferred_scheme`. 1050 Third party code that creates new virtual environments should use the new 1051 *venv* installation scheme to determine the paths, as does :mod:`venv`. 1052 (Contributed by Miro Hrončok in :issue:`45413`.) 1053 1054 1055.. _whatsnew311-tempfile: 1056 1057tempfile 1058-------- 1059 1060* :class:`~tempfile.SpooledTemporaryFile` objects now fully implement the methods 1061 of :class:`io.BufferedIOBase` or :class:`io.TextIOBase` 1062 (depending on file mode). 1063 This lets them work correctly with APIs that expect file-like objects, 1064 such as compression modules. 1065 (Contributed by Carey Metcalfe in :gh:`70363`.) 1066 1067* As of 3.11.10 on Windows, the default mode ``0o700`` used by 1068 :func:`tempfile.mkdtemp` now limits access to the new directory due to 1069 changes to :func:`os.mkdir`. This is a mitigation for CVE-2024-4030. 1070 (Contributed by Steve Dower in :gh:`118486`.) 1071 1072 1073.. _whatsnew311-threading: 1074 1075threading 1076--------- 1077 1078* On Unix, if the ``sem_clockwait()`` function is available in the C library 1079 (glibc 2.30 and newer), the :meth:`threading.Lock.acquire` method now uses 1080 the monotonic clock (:data:`time.CLOCK_MONOTONIC`) for the timeout, rather 1081 than using the system clock (:data:`time.CLOCK_REALTIME`), to not be affected 1082 by system clock changes. 1083 (Contributed by Victor Stinner in :issue:`41710`.) 1084 1085 1086.. _whatsnew311-time: 1087 1088time 1089---- 1090 1091* On Unix, :func:`time.sleep` now uses the ``clock_nanosleep()`` or 1092 ``nanosleep()`` function, if available, which has a resolution of 1 nanosecond 1093 (10\ :sup:`-9` seconds), rather than using ``select()`` which has a resolution 1094 of 1 microsecond (10\ :sup:`-6` seconds). 1095 (Contributed by Benjamin Szőke and Victor Stinner in :issue:`21302`.) 1096 1097* On Windows 8.1 and newer, :func:`time.sleep` now uses a waitable timer based 1098 on `high-resolution timers 1099 <https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/high-resolution-timers>`_ 1100 which has a resolution of 100 nanoseconds (10\ :sup:`-7` seconds). Previously, 1101 it had a resolution of 1 millisecond (10\ :sup:`-3` seconds). 1102 (Contributed by Benjamin Szőke, Dong-hee Na, Eryk Sun and Victor Stinner in :issue:`21302` and :issue:`45429`.) 1103 1104 1105.. _whatsnew311-tkinter: 1106 1107tkinter 1108------- 1109 1110* Added method ``info_patchlevel()`` which returns the exact version of 1111 the Tcl library as a named tuple similar to :data:`sys.version_info`. 1112 (Contributed by Serhiy Storchaka in :gh:`91827`.) 1113 1114 1115.. _whatsnew311-traceback: 1116 1117traceback 1118--------- 1119 1120* Add :func:`traceback.StackSummary.format_frame_summary` to allow users 1121 to override which frames appear in the traceback, and how they are 1122 formatted. 1123 (Contributed by Ammar Askar in :issue:`44569`.) 1124 1125* Add :func:`traceback.TracebackException.print`, which prints the 1126 formatted :exc:`~traceback.TracebackException` instance to a file. 1127 (Contributed by Irit Katriel in :issue:`33809`.) 1128 1129 1130.. _whatsnew311-typing: 1131 1132typing 1133------ 1134 1135For major changes, see :ref:`new-feat-related-type-hints-311`. 1136 1137* Add :func:`typing.assert_never` and :class:`typing.Never`. 1138 :func:`typing.assert_never` is useful for asking a type checker to confirm 1139 that a line of code is not reachable. At runtime, it raises an 1140 :exc:`AssertionError`. 1141 (Contributed by Jelle Zijlstra in :gh:`90633`.) 1142 1143* Add :func:`typing.reveal_type`. This is useful for asking a type checker 1144 what type it has inferred for a given expression. At runtime it prints 1145 the type of the received value. 1146 (Contributed by Jelle Zijlstra in :gh:`90572`.) 1147 1148* Add :func:`typing.assert_type`. This is useful for asking a type checker 1149 to confirm that the type it has inferred for a given expression matches 1150 the given type. At runtime it simply returns the received value. 1151 (Contributed by Jelle Zijlstra in :gh:`90638`.) 1152 1153* :data:`typing.TypedDict` types can now be generic. (Contributed by 1154 Samodya Abeysiriwardane in :gh:`89026`.) 1155 1156* :class:`~typing.NamedTuple` types can now be generic. 1157 (Contributed by Serhiy Storchaka in :issue:`43923`.) 1158 1159* Allow subclassing of :class:`typing.Any`. This is useful for avoiding 1160 type checker errors related to highly dynamic class, such as mocks. 1161 (Contributed by Shantanu Jain in :gh:`91154`.) 1162 1163* The :func:`typing.final` decorator now sets the ``__final__`` attributed on 1164 the decorated object. 1165 (Contributed by Jelle Zijlstra in :gh:`90500`.) 1166 1167* The :func:`typing.get_overloads` function can be used for introspecting 1168 the overloads of a function. :func:`typing.clear_overloads` can be used 1169 to clear all registered overloads of a function. 1170 (Contributed by Jelle Zijlstra in :gh:`89263`.) 1171 1172* The :meth:`~object.__init__` method of :class:`~typing.Protocol` subclasses 1173 is now preserved. (Contributed by Adrian Garcia Badarasco in :gh:`88970`.) 1174 1175* The representation of empty tuple types (``Tuple[()]``) is simplified. 1176 This affects introspection, e.g. ``get_args(Tuple[()])`` now evaluates 1177 to ``()`` instead of ``((),)``. 1178 (Contributed by Serhiy Storchaka in :gh:`91137`.) 1179 1180* Loosen runtime requirements for type annotations by removing the callable 1181 check in the private ``typing._type_check`` function. (Contributed by 1182 Gregory Beauregard in :gh:`90802`.) 1183 1184* :func:`typing.get_type_hints` now supports evaluating strings as forward 1185 references in :ref:`PEP 585 generic aliases <types-genericalias>`. 1186 (Contributed by Niklas Rosenstein in :gh:`85542`.) 1187 1188* :func:`typing.get_type_hints` no longer adds :data:`~typing.Optional` 1189 to parameters with ``None`` as a default. (Contributed by Nikita Sobolev 1190 in :gh:`90353`.) 1191 1192* :func:`typing.get_type_hints` now supports evaluating bare stringified 1193 :data:`~typing.ClassVar` annotations. (Contributed by Gregory Beauregard 1194 in :gh:`90711`.) 1195 1196* :func:`typing.no_type_check` no longer modifies external classes and functions. 1197 It also now correctly marks classmethods as not to be type checked. (Contributed 1198 by Nikita Sobolev in :gh:`90729`.) 1199 1200 1201.. _whatsnew311-unicodedata: 1202 1203unicodedata 1204----------- 1205 1206* The Unicode database has been updated to version 14.0.0. 1207 (Contributed by Benjamin Peterson in :issue:`45190`). 1208 1209 1210.. _whatsnew311-unittest: 1211 1212unittest 1213-------- 1214 1215* Added methods :meth:`~unittest.TestCase.enterContext` and 1216 :meth:`~unittest.TestCase.enterClassContext` of class 1217 :class:`~unittest.TestCase`, method 1218 :meth:`~unittest.IsolatedAsyncioTestCase.enterAsyncContext` of 1219 class :class:`~unittest.IsolatedAsyncioTestCase` and function 1220 :func:`unittest.enterModuleContext`. 1221 (Contributed by Serhiy Storchaka in :issue:`45046`.) 1222 1223 1224.. _whatsnew311-venv: 1225 1226venv 1227---- 1228 1229* When new Python virtual environments are created, the *venv* 1230 :ref:`sysconfig installation scheme <installation_paths>` is used 1231 to determine the paths inside the environment. 1232 When Python runs in a virtual environment, the same installation scheme 1233 is the default. 1234 That means that downstream distributors can change the default sysconfig install 1235 scheme without changing behavior of virtual environments. 1236 Third party code that also creates new virtual environments should do the same. 1237 (Contributed by Miro Hrončok in :issue:`45413`.) 1238 1239 1240.. _whatsnew311-warnings: 1241 1242warnings 1243-------- 1244 1245* :func:`warnings.catch_warnings` now accepts arguments for :func:`warnings.simplefilter`, 1246 providing a more concise way to locally ignore warnings or convert them to errors. 1247 (Contributed by Zac Hatfield-Dodds in :issue:`47074`.) 1248 1249 1250.. _whatsnew311-zipfile: 1251 1252zipfile 1253------- 1254 1255* Added support for specifying member name encoding for reading metadata 1256 in a :class:`~zipfile.ZipFile`'s directory and file headers. 1257 (Contributed by Stephen J. Turnbull and Serhiy Storchaka in :issue:`28080`.) 1258 1259* Added :meth:`ZipFile.mkdir() <zipfile.ZipFile.mkdir>` 1260 for creating new directories inside ZIP archives. 1261 (Contributed by Sam Ezeh in :gh:`49083`.) 1262 1263* Added :attr:`~zipfile.Path.stem`, :attr:`~zipfile.Path.suffix` 1264 and :attr:`~zipfile.Path.suffixes` to :class:`zipfile.Path`. 1265 (Contributed by Miguel Brito in :gh:`88261`.) 1266 1267 1268.. _whatsnew311-optimizations: 1269 1270Optimizations 1271============= 1272 1273This section covers specific optimizations independent of the 1274:ref:`whatsnew311-faster-cpython` project, which is covered in its own section. 1275 1276* The compiler now optimizes simple 1277 :ref:`printf-style % formatting <old-string-formatting>` on string literals 1278 containing only the format codes ``%s``, ``%r`` and ``%a`` and makes it as 1279 fast as a corresponding :term:`f-string` expression. 1280 (Contributed by Serhiy Storchaka in :issue:`28307`.) 1281 1282* Integer division (``//``) is better tuned for optimization by compilers. 1283 It is now around 20% faster on x86-64 when dividing an :class:`int` 1284 by a value smaller than ``2**30``. 1285 (Contributed by Gregory P. Smith and Tim Peters in :gh:`90564`.) 1286 1287* :func:`sum` is now nearly 30% faster for integers smaller than ``2**30``. 1288 (Contributed by Stefan Behnel in :gh:`68264`.) 1289 1290* Resizing lists is streamlined for the common case, 1291 speeding up :meth:`list.append` by ≈15% 1292 and simple :term:`list comprehension`\s by up to 20-30% 1293 (Contributed by Dennis Sweeney in :gh:`91165`.) 1294 1295* Dictionaries don't store hash values when all keys are Unicode objects, 1296 decreasing :class:`dict` size. 1297 For example, ``sys.getsizeof(dict.fromkeys("abcdefg"))`` 1298 is reduced from 352 bytes to 272 bytes (23% smaller) on 64-bit platforms. 1299 (Contributed by Inada Naoki in :issue:`46845`.) 1300 1301* Using :class:`asyncio.DatagramProtocol` is now orders of magnitude faster 1302 when transferring large files over UDP, 1303 with speeds over 100 times higher for a ≈60 MiB file. 1304 (Contributed by msoxzw in :gh:`91487`.) 1305 1306* :mod:`math` functions :func:`~math.comb` and :func:`~math.perm` are now 1307 ≈10 times faster for large arguments (with a larger speedup for larger *k*). 1308 (Contributed by Serhiy Storchaka in :issue:`37295`.) 1309 1310* The :mod:`statistics` functions :func:`~statistics.mean`, 1311 :func:`~statistics.variance` and :func:`~statistics.stdev` now consume 1312 iterators in one pass rather than converting them to a :class:`list` first. 1313 This is twice as fast and can save substantial memory. 1314 (Contributed by Raymond Hettinger in :gh:`90415`.) 1315 1316* :func:`unicodedata.normalize` 1317 now normalizes pure-ASCII strings in constant time. 1318 (Contributed by Dong-hee Na in :issue:`44987`.) 1319 1320 1321.. _whatsnew311-faster-cpython: 1322 1323Faster CPython 1324============== 1325 1326CPython 3.11 is an average of 1327`25% faster <https://github.com/faster-cpython/ideas#published-results>`_ 1328than CPython 3.10 as measured with the 1329`pyperformance <https://github.com/python/pyperformance>`_ benchmark suite, 1330when compiled with GCC on Ubuntu Linux. 1331Depending on your workload, the overall speedup could be 10-60%. 1332 1333This project focuses on two major areas in Python: 1334:ref:`whatsnew311-faster-startup` and :ref:`whatsnew311-faster-runtime`. 1335Optimizations not covered by this project are listed separately under 1336:ref:`whatsnew311-optimizations`. 1337 1338 1339.. _whatsnew311-faster-startup: 1340 1341Faster Startup 1342-------------- 1343 1344.. _whatsnew311-faster-imports: 1345 1346Frozen imports / Static code objects 1347^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1348 1349Python caches :term:`bytecode` in the :ref:`__pycache__ <tut-pycache>` 1350directory to speed up module loading. 1351 1352Previously in 3.10, Python module execution looked like this: 1353 1354.. code-block:: text 1355 1356 Read __pycache__ -> Unmarshal -> Heap allocated code object -> Evaluate 1357 1358In Python 3.11, the core modules essential for Python startup are "frozen". 1359This means that their :ref:`codeobjects` (and bytecode) 1360are statically allocated by the interpreter. 1361This reduces the steps in module execution process to: 1362 1363.. code-block:: text 1364 1365 Statically allocated code object -> Evaluate 1366 1367Interpreter startup is now 10-15% faster in Python 3.11. This has a big 1368impact for short-running programs using Python. 1369 1370(Contributed by Eric Snow, Guido van Rossum and Kumar Aditya in many issues.) 1371 1372 1373.. _whatsnew311-faster-runtime: 1374 1375Faster Runtime 1376-------------- 1377 1378.. _whatsnew311-lazy-python-frames: 1379 1380Cheaper, lazy Python frames 1381^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1382 1383Python frames, holding execution information, 1384are created whenever Python calls a Python function. 1385The following are new frame optimizations: 1386 1387- Streamlined the frame creation process. 1388- Avoided memory allocation by generously re-using frame space on the C stack. 1389- Streamlined the internal frame struct to contain only essential information. 1390 Frames previously held extra debugging and memory management information. 1391 1392Old-style :ref:`frame objects <frame-objects>` 1393are now created only when requested by debuggers 1394or by Python introspection functions such as :func:`sys._getframe` and 1395:func:`inspect.currentframe`. For most user code, no frame objects are 1396created at all. As a result, nearly all Python functions calls have sped 1397up significantly. We measured a 3-7% speedup in pyperformance. 1398 1399(Contributed by Mark Shannon in :issue:`44590`.) 1400 1401 1402.. _inline-calls: 1403.. _whatsnew311-inline-calls: 1404 1405Inlined Python function calls 1406^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1407 1408During a Python function call, Python will call an evaluating C function to 1409interpret that function's code. This effectively limits pure Python recursion to 1410what's safe for the C stack. 1411 1412In 3.11, when CPython detects Python code calling another Python function, 1413it sets up a new frame, and "jumps" to the new code inside the new frame. This 1414avoids calling the C interpreting function altogether. 1415 1416Most Python function calls now consume no C stack space, speeding them up. 1417In simple recursive functions like fibonacci or 1418factorial, we observed a 1.7x speedup. This also means recursive functions 1419can recurse significantly deeper 1420(if the user increases the recursion limit with :func:`sys.setrecursionlimit`). 1421We measured a 1-3% improvement in pyperformance. 1422 1423(Contributed by Pablo Galindo and Mark Shannon in :issue:`45256`.) 1424 1425 1426.. _whatsnew311-pep659: 1427 1428PEP 659: Specializing Adaptive Interpreter 1429^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1430 1431:pep:`659` is one of the key parts of the Faster CPython project. The general 1432idea is that while Python is a dynamic language, most code has regions where 1433objects and types rarely change. This concept is known as *type stability*. 1434 1435At runtime, Python will try to look for common patterns and type stability 1436in the executing code. Python will then replace the current operation with a 1437more specialized one. This specialized operation uses fast paths available only 1438to those use cases/types, which generally outperform their generic 1439counterparts. This also brings in another concept called *inline caching*, where 1440Python caches the results of expensive operations directly in the 1441:term:`bytecode`. 1442 1443The specializer will also combine certain common instruction pairs into one 1444superinstruction, reducing the overhead during execution. 1445 1446Python will only specialize 1447when it sees code that is "hot" (executed multiple times). This prevents Python 1448from wasting time on run-once code. Python can also de-specialize when code is 1449too dynamic or when the use changes. Specialization is attempted periodically, 1450and specialization attempts are not too expensive, 1451allowing specialization to adapt to new circumstances. 1452 1453(PEP written by Mark Shannon, with ideas inspired by Stefan Brunthaler. 1454See :pep:`659` for more information. Implementation by Mark Shannon and Brandt 1455Bucher, with additional help from Irit Katriel and Dennis Sweeney.) 1456 1457.. 1458 If I missed out anyone, please add them. 1459 1460+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1461| Operation | Form | Specialization | Operation speedup | Contributor(s) | 1462| | | | (up to) | | 1463+===============+====================+=======================================================+===================+===================+ 1464| Binary | ``x + x`` | Binary add, multiply and subtract for common types | 10% | Mark Shannon, | 1465| operations | | such as :class:`int`, :class:`float` and :class:`str` | | Dong-hee Na, | 1466| | ``x - x`` | take custom fast paths for their underlying types. | | Brandt Bucher, | 1467| | | | | Dennis Sweeney | 1468| | ``x * x`` | | | | 1469+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1470| Subscript | ``a[i]`` | Subscripting container types such as :class:`list`, | 10-25% | Irit Katriel, | 1471| | | :class:`tuple` and :class:`dict` directly index | | Mark Shannon | 1472| | | the underlying data structures. | | | 1473| | | | | | 1474| | | Subscripting custom :meth:`~object.__getitem__` | | | 1475| | | is also inlined similar to :ref:`inline-calls`. | | | 1476+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1477| Store | ``a[i] = z`` | Similar to subscripting specialization above. | 10-25% | Dennis Sweeney | 1478| subscript | | | | | 1479+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1480| Calls | ``f(arg)`` | Calls to common builtin (C) functions and types such | 20% | Mark Shannon, | 1481| | | as :func:`len` and :class:`str` directly call their | | Ken Jin | 1482| | ``C(arg)`` | underlying C version. This avoids going through the | | | 1483| | | internal calling convention. | | | 1484+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1485| Load | ``print`` | The object's index in the globals/builtins namespace | [#load-global]_ | Mark Shannon | 1486| global | | is cached. Loading globals and builtins require | | | 1487| variable | ``len`` | zero namespace lookups. | | | 1488+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1489| Load | ``o.attr`` | Similar to loading global variables. The attribute's | [#load-attr]_ | Mark Shannon | 1490| attribute | | index inside the class/object's namespace is cached. | | | 1491| | | In most cases, attribute loading will require zero | | | 1492| | | namespace lookups. | | | 1493+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1494| Load | ``o.meth()`` | The actual address of the method is cached. Method | 10-20% | Ken Jin, | 1495| methods for | | loading now has no namespace lookups -- even for | | Mark Shannon | 1496| call | | classes with long inheritance chains. | | | 1497+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1498| Store | ``o.attr = z`` | Similar to load attribute optimization. | 2% | Mark Shannon | 1499| attribute | | | in pyperformance | | 1500+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1501| Unpack | ``*seq`` | Specialized for common containers such as | 8% | Brandt Bucher | 1502| Sequence | | :class:`list` and :class:`tuple`. | | | 1503| | | Avoids internal calling convention. | | | 1504+---------------+--------------------+-------------------------------------------------------+-------------------+-------------------+ 1505 1506.. [#load-global] A similar optimization already existed since Python 3.8. 1507 3.11 specializes for more forms and reduces some overhead. 1508 1509.. [#load-attr] A similar optimization already existed since Python 3.10. 1510 3.11 specializes for more forms. Furthermore, all attribute loads should 1511 be sped up by :issue:`45947`. 1512 1513 1514.. _whatsnew311-faster-cpython-misc: 1515 1516Misc 1517---- 1518 1519* Objects now require less memory due to lazily created object namespaces. 1520 Their namespace dictionaries now also share keys more freely. 1521 (Contributed Mark Shannon in :issue:`45340` and :issue:`40116`.) 1522 1523* "Zero-cost" exceptions are implemented, eliminating the cost 1524 of :keyword:`try` statements when no exception is raised. 1525 (Contributed by Mark Shannon in :issue:`40222`.) 1526 1527* A more concise representation of exceptions in the interpreter reduced the 1528 time required for catching an exception by about 10%. 1529 (Contributed by Irit Katriel in :issue:`45711`.) 1530 1531* :mod:`re`'s regular expression matching engine has been partially refactored, 1532 and now uses computed gotos (or "threaded code") on supported platforms. As a 1533 result, Python 3.11 executes the `pyperformance regular expression benchmarks 1534 <https://pyperformance.readthedocs.io/benchmarks.html#regex-dna>`_ up to 10% 1535 faster than Python 3.10. 1536 (Contributed by Brandt Bucher in :gh:`91404`.) 1537 1538 1539.. _whatsnew311-faster-cpython-faq: 1540 1541FAQ 1542--- 1543 1544.. _faster-cpython-faq-my-code: 1545 1546How should I write my code to utilize these speedups? 1547^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1548 1549Write Pythonic code that follows common best practices; 1550you don't have to change your code. 1551The Faster CPython project optimizes for common code patterns we observe. 1552 1553 1554.. _faster-cpython-faq-memory: 1555 1556Will CPython 3.11 use more memory? 1557^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1558 1559Maybe not; we don't expect memory use to exceed 20% higher than 3.10. 1560This is offset by memory optimizations for frame objects and object 1561dictionaries as mentioned above. 1562 1563 1564.. _faster-cpython-ymmv: 1565 1566I don't see any speedups in my workload. Why? 1567^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1568 1569Certain code won't have noticeable benefits. If your code spends most of 1570its time on I/O operations, or already does most of its 1571computation in a C extension library like NumPy, there won't be significant 1572speedups. This project currently benefits pure-Python workloads the most. 1573 1574Furthermore, the pyperformance figures are a geometric mean. Even within the 1575pyperformance benchmarks, certain benchmarks have slowed down slightly, while 1576others have sped up by nearly 2x! 1577 1578 1579.. _faster-cpython-jit: 1580 1581Is there a JIT compiler? 1582^^^^^^^^^^^^^^^^^^^^^^^^ 1583 1584No. We're still exploring other optimizations. 1585 1586 1587.. _whatsnew311-faster-cpython-about: 1588 1589About 1590----- 1591 1592Faster CPython explores optimizations for :term:`CPython`. The main team is 1593funded by Microsoft to work on this full-time. Pablo Galindo Salgado is also 1594funded by Bloomberg LP to work on the project part-time. Finally, many 1595contributors are volunteers from the community. 1596 1597 1598.. _whatsnew311-bytecode-changes: 1599 1600CPython bytecode changes 1601======================== 1602 1603The bytecode now contains inline cache entries, 1604which take the form of the newly-added :opcode:`CACHE` instructions. 1605Many opcodes expect to be followed by an exact number of caches, 1606and instruct the interpreter to skip over them at runtime. 1607Populated caches can look like arbitrary instructions, 1608so great care should be taken when reading or modifying 1609raw, adaptive bytecode containing quickened data. 1610 1611 1612.. _whatsnew311-added-opcodes: 1613 1614New opcodes 1615----------- 1616 1617* :opcode:`ASYNC_GEN_WRAP`, :opcode:`RETURN_GENERATOR` and :opcode:`SEND`, 1618 used in generators and co-routines. 1619 1620* :opcode:`COPY_FREE_VARS`, 1621 which avoids needing special caller-side code for closures. 1622 1623* :opcode:`JUMP_BACKWARD_NO_INTERRUPT`, 1624 for use in certain loops where handling interrupts is undesirable. 1625 1626* :opcode:`MAKE_CELL`, to create :ref:`cell-objects`. 1627 1628* :opcode:`CHECK_EG_MATCH` and :opcode:`PREP_RERAISE_STAR`, 1629 to handle the :ref:`new exception groups and except* <whatsnew311-pep654>` 1630 added in :pep:`654`. 1631 1632* :opcode:`PUSH_EXC_INFO`, for use in exception handlers. 1633 1634* :opcode:`RESUME`, a no-op, 1635 for internal tracing, debugging and optimization checks. 1636 1637 1638.. _whatsnew311-replaced-opcodes: 1639 1640Replaced opcodes 1641---------------- 1642 1643+------------------------------------+-----------------------------------+-----------------------------------------+ 1644| Replaced Opcode(s) | New Opcode(s) | Notes | 1645+====================================+===================================+=========================================+ 1646| | :opcode:`!BINARY_*` | :opcode:`BINARY_OP` | Replaced all numeric binary/in-place | 1647| | :opcode:`!INPLACE_*` | | opcodes with a single opcode | 1648+------------------------------------+-----------------------------------+-----------------------------------------+ 1649| | :opcode:`!CALL_FUNCTION` | | :opcode:`CALL` | Decouples argument shifting for methods | 1650| | :opcode:`!CALL_FUNCTION_KW` | | :opcode:`KW_NAMES` | from handling of keyword arguments; | 1651| | :opcode:`!CALL_METHOD` | | :opcode:`PRECALL` | allows better specialization of calls | 1652| | | :opcode:`PUSH_NULL` | | 1653+------------------------------------+-----------------------------------+-----------------------------------------+ 1654| | :opcode:`!DUP_TOP` | | :opcode:`COPY` | Stack manipulation instructions | 1655| | :opcode:`!DUP_TOP_TWO` | | :opcode:`SWAP` | | 1656| | :opcode:`!ROT_TWO` | | | 1657| | :opcode:`!ROT_THREE` | | | 1658| | :opcode:`!ROT_FOUR` | | | 1659| | :opcode:`!ROT_N` | | | 1660+------------------------------------+-----------------------------------+-----------------------------------------+ 1661| | :opcode:`!JUMP_IF_NOT_EXC_MATCH` | | :opcode:`CHECK_EXC_MATCH` | Now performs check but doesn't jump | 1662+------------------------------------+-----------------------------------+-----------------------------------------+ 1663| | :opcode:`!JUMP_ABSOLUTE` | | :opcode:`JUMP_BACKWARD` | See [#bytecode-jump]_; | 1664| | :opcode:`!POP_JUMP_IF_FALSE` | | :opcode:`POP_JUMP_BACKWARD_IF_* | ``TRUE``, ``FALSE``, | 1665| | :opcode:`!POP_JUMP_IF_TRUE` | <POP_JUMP_BACKWARD_IF_TRUE>` | ``NONE`` and ``NOT_NONE`` variants | 1666| | | :opcode:`POP_JUMP_FORWARD_IF_* | for each direction | 1667| | <POP_JUMP_FORWARD_IF_TRUE>` | | 1668+------------------------------------+-----------------------------------+-----------------------------------------+ 1669| | :opcode:`!SETUP_WITH` | :opcode:`BEFORE_WITH` | :keyword:`with` block setup | 1670| | :opcode:`!SETUP_ASYNC_WITH` | | | 1671+------------------------------------+-----------------------------------+-----------------------------------------+ 1672 1673.. [#bytecode-jump] All jump opcodes are now relative, including the 1674 existing :opcode:`JUMP_IF_TRUE_OR_POP` and :opcode:`JUMP_IF_FALSE_OR_POP`. 1675 The argument is now an offset from the current instruction 1676 rather than an absolute location. 1677 1678 1679.. _whatsnew311-changed-opcodes: 1680.. _whatsnew311-removed-opcodes: 1681.. _whatsnew311-changed-removed-opcodes: 1682 1683Changed/removed opcodes 1684----------------------- 1685 1686* Changed :opcode:`MATCH_CLASS` and :opcode:`MATCH_KEYS` 1687 to no longer push an additional boolean value to indicate success/failure. 1688 Instead, ``None`` is pushed on failure 1689 in place of the tuple of extracted values. 1690 1691* Changed opcodes that work with exceptions to reflect them 1692 now being represented as one item on the stack instead of three 1693 (see :gh:`89874`). 1694 1695* Removed :opcode:`!COPY_DICT_WITHOUT_KEYS`, :opcode:`!GEN_START`, 1696 :opcode:`!POP_BLOCK`, :opcode:`!SETUP_FINALLY` and :opcode:`!YIELD_FROM`. 1697 1698 1699.. _whatsnew311-deprecated: 1700.. _whatsnew311-python-api-deprecated: 1701 1702Deprecated 1703========== 1704 1705This section lists Python APIs that have been deprecated in Python 3.11. 1706 1707Deprecated C APIs are :ref:`listed separately <whatsnew311-c-api-deprecated>`. 1708 1709 1710.. _whatsnew311-deprecated-language: 1711.. _whatsnew311-deprecated-builtins: 1712 1713Language/Builtins 1714----------------- 1715 1716* Chaining :class:`classmethod` descriptors (introduced in :issue:`19072`) 1717 is now deprecated. It can no longer be used to wrap other descriptors 1718 such as :class:`property`. The core design of this feature was flawed 1719 and caused a number of downstream problems. To "pass-through" a 1720 :class:`classmethod`, consider using the :attr:`!__wrapped__` attribute 1721 that was added in Python 3.10. 1722 (Contributed by Raymond Hettinger in :gh:`89519`.) 1723 1724* Octal escapes in string and bytes literals with values larger than ``0o377`` 1725 (255 in decimal) now produce a :exc:`DeprecationWarning`. 1726 In a future Python version, they will raise a :exc:`SyntaxWarning` and 1727 eventually a :exc:`SyntaxError`. 1728 (Contributed by Serhiy Storchaka in :gh:`81548`.) 1729 1730* The delegation of :func:`int` to :meth:`~object.__trunc__` is now deprecated. 1731 Calling ``int(a)`` when ``type(a)`` implements :meth:`!__trunc__` but not 1732 :meth:`~object.__int__` or :meth:`~object.__index__` now raises 1733 a :exc:`DeprecationWarning`. 1734 (Contributed by Zackery Spytz in :issue:`44977`.) 1735 1736 1737.. _whatsnew311-deprecated-modules: 1738 1739Modules 1740------- 1741 1742.. _whatsnew311-pep594: 1743 1744* :pep:`594` led to the deprecations of the following modules 1745 slated for removal in Python 3.13: 1746 1747 +---------------------+---------------------+---------------------+---------------------+---------------------+ 1748 | :mod:`aifc` | :mod:`chunk` | :mod:`msilib` | :mod:`pipes` | :mod:`telnetlib` | 1749 +---------------------+---------------------+---------------------+---------------------+---------------------+ 1750 | :mod:`audioop` | :mod:`crypt` | :mod:`nis` | :mod:`sndhdr` | :mod:`uu` | 1751 +---------------------+---------------------+---------------------+---------------------+---------------------+ 1752 | :mod:`cgi` | :mod:`imghdr` | :mod:`nntplib` | :mod:`spwd` | :mod:`xdrlib` | 1753 +---------------------+---------------------+---------------------+---------------------+---------------------+ 1754 | :mod:`cgitb` | :mod:`mailcap` | :mod:`ossaudiodev` | :mod:`sunau` | | 1755 +---------------------+---------------------+---------------------+---------------------+---------------------+ 1756 1757 (Contributed by Brett Cannon in :issue:`47061` and Victor Stinner in 1758 :gh:`68966`.) 1759 1760* The :mod:`asynchat`, :mod:`asyncore` and :mod:`smtpd` modules have been 1761 deprecated since at least Python 3.6. Their documentation and deprecation 1762 warnings have now been updated to note they will be removed in Python 3.12. 1763 (Contributed by Hugo van Kemenade in :issue:`47022`.) 1764 1765* The :mod:`lib2to3` package and :ref:`2to3 <2to3-reference>` tool 1766 are now deprecated and may not be able to parse Python 3.10 or newer. 1767 See :pep:`617`, introducing the new PEG parser, for details. 1768 (Contributed by Victor Stinner in :issue:`40360`.) 1769 1770* Undocumented modules :mod:`!sre_compile`, :mod:`!sre_constants` 1771 and :mod:`!sre_parse` are now deprecated. 1772 (Contributed by Serhiy Storchaka in :issue:`47152`.) 1773 1774 1775.. _whatsnew311-deprecated-stdlib: 1776 1777Standard Library 1778---------------- 1779 1780* The following have been deprecated in :mod:`configparser` since Python 3.2. 1781 Their deprecation warnings have now been updated to note they will be removed 1782 in Python 3.12: 1783 1784 * the :class:`!configparser.SafeConfigParser` class 1785 * the :attr:`!configparser.ParsingError.filename` property 1786 * the :meth:`configparser.RawConfigParser.readfp` method 1787 1788 (Contributed by Hugo van Kemenade in :issue:`45173`.) 1789 1790* :class:`!configparser.LegacyInterpolation` has been deprecated in the docstring 1791 since Python 3.2, and is not listed in the :mod:`configparser` documentation. 1792 It now emits a :exc:`DeprecationWarning` and will be removed 1793 in Python 3.13. Use :class:`configparser.BasicInterpolation` or 1794 :class:`configparser.ExtendedInterpolation` instead. 1795 (Contributed by Hugo van Kemenade in :issue:`46607`.) 1796 1797* The older set of :mod:`importlib.resources` functions were deprecated 1798 in favor of the replacements added in Python 3.9 1799 and will be removed in a future Python version, 1800 due to not supporting resources located within package subdirectories: 1801 1802 * :func:`importlib.resources.contents` 1803 * :func:`importlib.resources.is_resource` 1804 * :func:`importlib.resources.open_binary` 1805 * :func:`importlib.resources.open_text` 1806 * :func:`importlib.resources.read_binary` 1807 * :func:`importlib.resources.read_text` 1808 * :func:`importlib.resources.path` 1809 1810* The :func:`locale.getdefaultlocale` function is deprecated and will be 1811 removed in Python 3.13. Use :func:`locale.setlocale`, 1812 :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>` and 1813 :func:`locale.getlocale` functions instead. 1814 (Contributed by Victor Stinner in :gh:`90817`.) 1815 1816* The :func:`locale.resetlocale` function is deprecated and will be 1817 removed in Python 3.13. Use ``locale.setlocale(locale.LC_ALL, "")`` instead. 1818 (Contributed by Victor Stinner in :gh:`90817`.) 1819 1820* Stricter rules will now be applied for numerical group references 1821 and group names in :ref:`regular expressions <re-syntax>`. 1822 Only sequences of ASCII digits will now be accepted as a numerical reference, 1823 and the group name in :class:`bytes` patterns and replacement strings 1824 can only contain ASCII letters, digits and underscores. 1825 For now, a deprecation warning is raised for syntax violating these rules. 1826 (Contributed by Serhiy Storchaka in :gh:`91760`.) 1827 1828* In the :mod:`re` module, the :func:`!re.template` function 1829 and the corresponding :data:`!re.TEMPLATE` and :data:`!re.T` flags 1830 are deprecated, as they were undocumented and lacked an obvious purpose. 1831 They will be removed in Python 3.13. 1832 (Contributed by Serhiy Storchaka and Miro Hrončok in :gh:`92728`.) 1833 1834* :func:`turtle.settiltangle` has been deprecated since Python 3.1; 1835 it now emits a deprecation warning and will be removed in Python 3.13. Use 1836 :func:`turtle.tiltangle` instead (it was earlier incorrectly marked 1837 as deprecated, and its docstring is now corrected). 1838 (Contributed by Hugo van Kemenade in :issue:`45837`.) 1839 1840* :class:`typing.Text`, which exists solely to provide compatibility support 1841 between Python 2 and Python 3 code, is now deprecated. Its removal is 1842 currently unplanned, but users are encouraged to use :class:`str` instead 1843 wherever possible. 1844 (Contributed by Alex Waygood in :gh:`92332`.) 1845 1846* The keyword argument syntax for constructing :data:`typing.TypedDict` types 1847 is now deprecated. Support will be removed in Python 3.13. (Contributed by 1848 Jingchen Ye in :gh:`90224`.) 1849 1850* :class:`!webbrowser.MacOSX` is deprecated and will be removed in Python 3.13. 1851 It is untested, undocumented, and not used by :mod:`webbrowser` itself. 1852 (Contributed by Dong-hee Na in :issue:`42255`.) 1853 1854* The behavior of returning a value from a :class:`~unittest.TestCase` and 1855 :class:`~unittest.IsolatedAsyncioTestCase` test methods (other than the 1856 default ``None`` value) is now deprecated. 1857 1858* Deprecated the following not-formally-documented :mod:`unittest` functions, 1859 scheduled for removal in Python 3.13: 1860 1861 * :func:`!unittest.findTestCases` 1862 * :func:`!unittest.makeSuite` 1863 * :func:`!unittest.getTestCaseNames` 1864 1865 Use :class:`~unittest.TestLoader` methods instead: 1866 1867 * :meth:`unittest.TestLoader.loadTestsFromModule` 1868 * :meth:`unittest.TestLoader.loadTestsFromTestCase` 1869 * :meth:`unittest.TestLoader.getTestCaseNames` 1870 1871 (Contributed by Erlend E. Aasland in :issue:`5846`.) 1872 1873* :meth:`~!unittest.TestProgram.usageExit` is marked deprecated, to be removed 1874 in 3.13. 1875 (Contributed by Carlos Damázio in :gh:`67048`.) 1876 1877 1878.. _whatsnew311-pending-removal: 1879.. _whatsnew311-python-api-pending-removal: 1880 1881Pending Removal in Python 3.12 1882============================== 1883 1884The following Python APIs have been deprecated in earlier Python releases, 1885and will be removed in Python 3.12. 1886 1887C APIs pending removal are 1888:ref:`listed separately <whatsnew311-c-api-pending-removal>`. 1889 1890* The :mod:`asynchat` module 1891* The :mod:`asyncore` module 1892* The :ref:`entire distutils package <distutils-deprecated>` 1893* The :mod:`imp` module 1894* The :class:`typing.io <typing.IO>` namespace 1895* The :class:`typing.re <typing.Pattern>` namespace 1896* :func:`!cgi.log` 1897* :func:`importlib.find_loader` 1898* :meth:`importlib.abc.Loader.module_repr` 1899* :meth:`importlib.abc.MetaPathFinder.find_module` 1900* :meth:`importlib.abc.PathEntryFinder.find_loader` 1901* :meth:`importlib.abc.PathEntryFinder.find_module` 1902* :meth:`!importlib.machinery.BuiltinImporter.find_module` 1903* :meth:`!importlib.machinery.BuiltinLoader.module_repr` 1904* :meth:`!importlib.machinery.FileFinder.find_loader` 1905* :meth:`!importlib.machinery.FileFinder.find_module` 1906* :meth:`!importlib.machinery.FrozenImporter.find_module` 1907* :meth:`!importlib.machinery.FrozenLoader.module_repr` 1908* :meth:`importlib.machinery.PathFinder.find_module` 1909* :meth:`!importlib.machinery.WindowsRegistryFinder.find_module` 1910* :func:`importlib.util.module_for_loader` 1911* :func:`!importlib.util.set_loader_wrapper` 1912* :func:`!importlib.util.set_package_wrapper` 1913* :class:`pkgutil.ImpImporter` 1914* :class:`pkgutil.ImpLoader` 1915* :meth:`pathlib.Path.link_to` 1916* :func:`!sqlite3.enable_shared_cache` 1917* :func:`!sqlite3.OptimizedUnicode` 1918* :envvar:`PYTHONTHREADDEBUG` environment variable 1919* The following deprecated aliases in :mod:`unittest`: 1920 1921 ============================ =============================== =============== 1922 Deprecated alias Method Name Deprecated in 1923 ============================ =============================== =============== 1924 ``failUnless`` :meth:`.assertTrue` 3.1 1925 ``failIf`` :meth:`.assertFalse` 3.1 1926 ``failUnlessEqual`` :meth:`.assertEqual` 3.1 1927 ``failIfEqual`` :meth:`.assertNotEqual` 3.1 1928 ``failUnlessAlmostEqual`` :meth:`.assertAlmostEqual` 3.1 1929 ``failIfAlmostEqual`` :meth:`.assertNotAlmostEqual` 3.1 1930 ``failUnlessRaises`` :meth:`.assertRaises` 3.1 1931 ``assert_`` :meth:`.assertTrue` 3.2 1932 ``assertEquals`` :meth:`.assertEqual` 3.2 1933 ``assertNotEquals`` :meth:`.assertNotEqual` 3.2 1934 ``assertAlmostEquals`` :meth:`.assertAlmostEqual` 3.2 1935 ``assertNotAlmostEquals`` :meth:`.assertNotAlmostEqual` 3.2 1936 ``assertRegexpMatches`` :meth:`.assertRegex` 3.2 1937 ``assertRaisesRegexp`` :meth:`.assertRaisesRegex` 3.2 1938 ``assertNotRegexpMatches`` :meth:`.assertNotRegex` 3.5 1939 ============================ =============================== =============== 1940 1941.. _whatsnew311-removed: 1942.. _whatsnew311-python-api-removed: 1943 1944Removed 1945======= 1946 1947This section lists Python APIs that have been removed in Python 3.11. 1948 1949Removed C APIs are :ref:`listed separately <whatsnew311-c-api-removed>`. 1950 1951* Removed the :func:`!@asyncio.coroutine` :term:`decorator` 1952 enabling legacy generator-based coroutines to be compatible with 1953 :keyword:`async` / :keyword:`await` code. 1954 The function has been deprecated since Python 3.8 and the removal was 1955 initially scheduled for Python 3.10. Use :keyword:`async def` instead. 1956 (Contributed by Illia Volochii in :issue:`43216`.) 1957 1958* Removed :class:`!asyncio.coroutines.CoroWrapper` used for wrapping legacy 1959 generator-based coroutine objects in the debug mode. 1960 (Contributed by Illia Volochii in :issue:`43216`.) 1961 1962* Due to significant security concerns, the *reuse_address* parameter of 1963 :meth:`asyncio.loop.create_datagram_endpoint`, disabled in Python 3.9, is 1964 now entirely removed. This is because of the behavior of the socket option 1965 ``SO_REUSEADDR`` in UDP. 1966 (Contributed by Hugo van Kemenade in :issue:`45129`.) 1967 1968* Removed the :mod:`!binhex` module, deprecated in Python 3.9. 1969 Also removed the related, similarly-deprecated :mod:`binascii` functions: 1970 1971 * :func:`!binascii.a2b_hqx` 1972 * :func:`!binascii.b2a_hqx` 1973 * :func:`!binascii.rlecode_hqx` 1974 * :func:`!binascii.rldecode_hqx` 1975 1976 The :func:`binascii.crc_hqx` function remains available. 1977 1978 (Contributed by Victor Stinner in :issue:`45085`.) 1979 1980* Removed the :mod:`distutils` ``bdist_msi`` command deprecated in Python 3.9. 1981 Use ``bdist_wheel`` (wheel packages) instead. 1982 (Contributed by Hugo van Kemenade in :issue:`45124`.) 1983 1984* Removed the :meth:`~object.__getitem__` methods of 1985 :class:`xml.dom.pulldom.DOMEventStream`, :class:`wsgiref.util.FileWrapper` 1986 and :class:`fileinput.FileInput`, deprecated since Python 3.9. 1987 (Contributed by Hugo van Kemenade in :issue:`45132`.) 1988 1989* Removed the deprecated :mod:`gettext` functions 1990 :func:`!lgettext`, :func:`!ldgettext`, 1991 :func:`!lngettext` and :func:`!ldngettext`. 1992 Also removed the :func:`!bind_textdomain_codeset` function, 1993 the :meth:`!NullTranslations.output_charset` and 1994 :meth:`!NullTranslations.set_output_charset` methods, 1995 and the *codeset* parameter of :func:`!translation` and :func:`!install`, 1996 since they are only used for the :func:`!l*gettext` functions. 1997 (Contributed by Dong-hee Na and Serhiy Storchaka in :issue:`44235`.) 1998 1999* Removed from the :mod:`inspect` module: 2000 2001 * The :func:`!getargspec` function, deprecated since Python 3.0; 2002 use :func:`inspect.signature` or :func:`inspect.getfullargspec` instead. 2003 2004 * The :func:`!formatargspec` function, deprecated since Python 3.5; 2005 use the :func:`inspect.signature` function 2006 or the :class:`inspect.Signature` object directly. 2007 2008 * The undocumented :meth:`!Signature.from_builtin` 2009 and :meth:`!Signature.from_function` methods, deprecated since Python 3.5; 2010 use the :meth:`Signature.from_callable() <inspect.Signature.from_callable>` 2011 method instead. 2012 2013 (Contributed by Hugo van Kemenade in :issue:`45320`.) 2014 2015* Removed the :meth:`~object.__class_getitem__` method 2016 from :class:`pathlib.PurePath`, 2017 because it was not used and added by mistake in previous versions. 2018 (Contributed by Nikita Sobolev in :issue:`46483`.) 2019 2020* Removed the :class:`!MailmanProxy` class in the :mod:`smtpd` module, 2021 as it is unusable without the external :mod:`!mailman` package. 2022 (Contributed by Dong-hee Na in :issue:`35800`.) 2023 2024* Removed the deprecated :meth:`!split` method of :class:`!_tkinter.TkappType`. 2025 (Contributed by Erlend E. Aasland in :issue:`38371`.) 2026 2027* Removed namespace package support from :mod:`unittest` discovery. 2028 It was introduced in Python 3.4 but has been broken since Python 3.7. 2029 (Contributed by Inada Naoki in :issue:`23882`.) 2030 2031* Removed the undocumented private :meth:`!float.__set_format__()` method, 2032 previously known as :meth:`!float.__setformat__()` in Python 3.7. 2033 Its docstring said: "You probably don't want to use this function. 2034 It exists mainly to be used in Python's test suite." 2035 (Contributed by Victor Stinner in :issue:`46852`.) 2036 2037* The :option:`!--experimental-isolated-subinterpreters` configure flag 2038 (and corresponding :c:macro:`!EXPERIMENTAL_ISOLATED_SUBINTERPRETERS` macro) 2039 have been removed. 2040 2041* `Pynche <https://pypi.org/project/pynche/>`_ 2042 --- The Pythonically Natural Color and Hue Editor --- has been moved out 2043 of ``Tools/scripts`` and is `being developed independently 2044 <https://gitlab.com/warsaw/pynche/-/tree/main>`_ from the Python source tree. 2045 2046 2047.. _whatsnew311-porting: 2048.. _whatsnew311-python-api-porting: 2049 2050Porting to Python 3.11 2051====================== 2052 2053This section lists previously described changes and other bugfixes 2054in the Python API that may require changes to your Python code. 2055 2056Porting notes for the C API are 2057:ref:`listed separately <whatsnew311-c-api-porting>`. 2058 2059* :func:`open`, :func:`io.open`, :func:`codecs.open` and 2060 :class:`fileinput.FileInput` no longer accept ``'U'`` ("universal newline") 2061 in the file mode. In Python 3, "universal newline" mode is used by default 2062 whenever a file is opened in text mode, 2063 and the ``'U'`` flag has been deprecated since Python 3.3. 2064 The :ref:`newline parameter <open-newline-parameter>` 2065 to these functions controls how universal newlines work. 2066 (Contributed by Victor Stinner in :issue:`37330`.) 2067 2068* :class:`ast.AST` node positions are now validated when provided to 2069 :func:`compile` and other related functions. If invalid positions are detected, 2070 a :exc:`ValueError` will be raised. (Contributed by Pablo Galindo in :gh:`93351`) 2071 2072* Prohibited passing non-:class:`concurrent.futures.ThreadPoolExecutor` 2073 executors to :meth:`asyncio.loop.set_default_executor` 2074 following a deprecation in Python 3.8. 2075 (Contributed by Illia Volochii in :issue:`43234`.) 2076 2077* :mod:`calendar`: The :class:`calendar.LocaleTextCalendar` and 2078 :class:`calendar.LocaleHTMLCalendar` classes now use 2079 :func:`locale.getlocale`, instead of using :func:`locale.getdefaultlocale`, 2080 if no locale is specified. 2081 (Contributed by Victor Stinner in :issue:`46659`.) 2082 2083* The :mod:`pdb` module now reads the :file:`.pdbrc` configuration file with 2084 the ``'UTF-8'`` encoding. 2085 (Contributed by Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి) in :issue:`41137`.) 2086 2087* The *population* parameter of :func:`random.sample` must be a sequence, 2088 and automatic conversion of :class:`set`\s to :class:`list`\s 2089 is no longer supported. Also, if the sample size 2090 is larger than the population size, a :exc:`ValueError` is raised. 2091 (Contributed by Raymond Hettinger in :issue:`40465`.) 2092 2093* The *random* optional parameter of :func:`random.shuffle` was removed. 2094 It was previously an arbitrary random function to use for the shuffle; 2095 now, :func:`random.random` (its previous default) will always be used. 2096 2097* In :mod:`re` :ref:`re-syntax`, global inline flags (e.g. ``(?i)``) 2098 can now only be used at the start of regular expressions. 2099 Using them elsewhere has been deprecated since Python 3.6. 2100 (Contributed by Serhiy Storchaka in :issue:`47066`.) 2101 2102* In the :mod:`re` module, several long-standing bugs where fixed that, 2103 in rare cases, could cause capture groups to get the wrong result. 2104 Therefore, this could change the captured output in these cases. 2105 (Contributed by Ma Lin in :issue:`35859`.) 2106 2107 2108.. _whatsnew311-build-changes: 2109 2110Build Changes 2111============= 2112 2113* CPython now has :pep:`11` :pep:`Tier 3 support <11#tier-3>` for 2114 cross compiling to the `WebAssembly <https://webassembly.org/>`_ platforms 2115 `Emscripten <https://emscripten.org/>`_ 2116 (``wasm32-unknown-emscripten``, i.e. Python in the browser) 2117 and `WebAssembly System Interface (WASI) <https://wasi.dev/>`_ 2118 (``wasm32-unknown-wasi``). 2119 The effort is inspired by previous work like `Pyodide <https://pyodide.org/>`_. 2120 These platforms provide a limited subset of POSIX APIs; Python standard 2121 libraries features and modules related to networking, processes, threading, 2122 signals, mmap, and users/groups are not available or don't work. 2123 (Emscripten contributed by Christian Heimes and Ethan Smith in :gh:`84461` 2124 and WASI contributed by Christian Heimes in :gh:`90473`; 2125 platforms promoted in :gh:`95085`) 2126 2127* Building CPython now requires: 2128 2129 * A `C11 <https://en.cppreference.com/w/c/11>`_ compiler and standard library. 2130 `Optional C11 features 2131 <https://en.wikipedia.org/wiki/C11_(C_standard_revision)#Optional_features>`_ 2132 are not required. 2133 (Contributed by Victor Stinner in :issue:`46656`, 2134 :issue:`45440` and :issue:`46640`.) 2135 2136 * Support for `IEEE 754 <https://en.wikipedia.org/wiki/IEEE_754>`_ 2137 floating point numbers. 2138 (Contributed by Victor Stinner in :issue:`46917`.) 2139 2140* The :c:macro:`!Py_NO_NAN` macro has been removed. 2141 Since CPython now requires IEEE 754 floats, NaN values are always available. 2142 (Contributed by Victor Stinner in :issue:`46656`.) 2143 2144* The :mod:`tkinter` package now requires `Tcl/Tk <https://www.tcl.tk>`_ 2145 version 8.5.12 or newer. 2146 (Contributed by Serhiy Storchaka in :issue:`46996`.) 2147 2148* Build dependencies, compiler flags, and linker flags for most stdlib 2149 extension modules are now detected by :program:`configure`. libffi, libnsl, 2150 libsqlite3, zlib, bzip2, liblzma, libcrypt, Tcl/Tk, and uuid flags 2151 are detected by `pkg-config 2152 <https://www.freedesktop.org/wiki/Software/pkg-config/>`_ (when available). 2153 :mod:`tkinter` now requires a pkg-config command 2154 to detect development settings for `Tcl/Tk`_ headers and libraries. 2155 (Contributed by Christian Heimes and Erlend Egeberg Aasland in 2156 :issue:`45847`, :issue:`45747`, and :issue:`45763`.) 2157 2158* libpython is no longer linked against libcrypt. 2159 (Contributed by Mike Gilbert in :issue:`45433`.) 2160 2161* CPython can now be built with the 2162 `ThinLTO <https://clang.llvm.org/docs/ThinLTO.html>`_ option 2163 via passing ``thin`` to :option:`--with-lto`, i.e. ``--with-lto=thin``. 2164 (Contributed by Dong-hee Na and Brett Holman in :issue:`44340`.) 2165 2166* Freelists for object structs can now be disabled. A new :program:`configure` 2167 option :option:`!--without-freelists` can be used to disable all freelists 2168 except empty tuple singleton. 2169 (Contributed by Christian Heimes in :issue:`45522`.) 2170 2171* ``Modules/Setup`` and ``Modules/makesetup`` have been improved and tied up. 2172 Extension modules can now be built through ``makesetup``. All except some 2173 test modules can be linked statically into a main binary or library. 2174 (Contributed by Brett Cannon and Christian Heimes in :issue:`45548`, 2175 :issue:`45570`, :issue:`45571`, and :issue:`43974`.) 2176 2177 .. note:: 2178 Use the environment variables :envvar:`!TCLTK_CFLAGS` and 2179 :envvar:`!TCLTK_LIBS` to manually specify the location of Tcl/Tk headers 2180 and libraries. The :program:`configure` options 2181 :option:`!--with-tcltk-includes` and :option:`!--with-tcltk-libs` 2182 have been removed. 2183 2184 On RHEL 7 and CentOS 7 the development packages do not provide ``tcl.pc`` 2185 and ``tk.pc``; use ``TCLTK_LIBS="-ltk8.5 -ltkstub8.5 -ltcl8.5"``. 2186 The directory ``Misc/rhel7`` contains ``.pc`` files and instructions 2187 on how to build Python with RHEL 7's and CentOS 7's Tcl/Tk and OpenSSL. 2188 2189* CPython will now use 30-bit digits by default for the Python :class:`int` 2190 implementation. Previously, the default was to use 30-bit digits on platforms 2191 with ``SIZEOF_VOID_P >= 8``, and 15-bit digits otherwise. It's still possible 2192 to explicitly request use of 15-bit digits via either the 2193 :option:`--enable-big-digits` option to the configure script 2194 or (for Windows) the ``PYLONG_BITS_IN_DIGIT`` variable in ``PC/pyconfig.h``, 2195 but this option may be removed at some point in the future. 2196 (Contributed by Mark Dickinson in :issue:`45569`.) 2197 2198 2199.. _whatsnew311-c-api: 2200 2201C API Changes 2202============= 2203 2204.. _whatsnew311-c-api-new-features: 2205 2206New Features 2207------------ 2208 2209* Add a new :c:func:`PyType_GetName` function to get type's short name. 2210 (Contributed by Hai Shi in :issue:`42035`.) 2211 2212* Add a new :c:func:`PyType_GetQualName` function to get type's qualified name. 2213 (Contributed by Hai Shi in :issue:`42035`.) 2214 2215* Add new :c:func:`PyThreadState_EnterTracing` and 2216 :c:func:`PyThreadState_LeaveTracing` functions to the limited C API to 2217 suspend and resume tracing and profiling. 2218 (Contributed by Victor Stinner in :issue:`43760`.) 2219 2220* Added the :c:data:`Py_Version` constant which bears the same value as 2221 :c:macro:`PY_VERSION_HEX`. 2222 (Contributed by Gabriele N. Tornetta in :issue:`43931`.) 2223 2224* :c:type:`Py_buffer` and APIs are now part of the limited API and the stable 2225 ABI: 2226 2227 * :c:func:`PyObject_CheckBuffer` 2228 * :c:func:`PyObject_GetBuffer` 2229 * :c:func:`PyBuffer_GetPointer` 2230 * :c:func:`PyBuffer_SizeFromFormat` 2231 * :c:func:`PyBuffer_ToContiguous` 2232 * :c:func:`PyBuffer_FromContiguous` 2233 * :c:func:`PyBuffer_CopyData` 2234 * :c:func:`PyBuffer_IsContiguous` 2235 * :c:func:`PyBuffer_FillContiguousStrides` 2236 * :c:func:`PyBuffer_FillInfo` 2237 * :c:func:`PyBuffer_Release` 2238 * :c:func:`PyMemoryView_FromBuffer` 2239 * :c:member:`~PyBufferProcs.bf_getbuffer` and 2240 :c:member:`~PyBufferProcs.bf_releasebuffer` type slots 2241 2242 (Contributed by Christian Heimes in :issue:`45459`.) 2243 2244* Added the :c:data:`PyType_GetModuleByDef` function, used to get the module 2245 in which a method was defined, in cases where this information is not 2246 available directly (via :c:type:`PyCMethod`). 2247 (Contributed by Petr Viktorin in :issue:`46613`.) 2248 2249* Add new functions to pack and unpack C double (serialize and deserialize): 2250 :c:func:`PyFloat_Pack2`, :c:func:`PyFloat_Pack4`, :c:func:`PyFloat_Pack8`, 2251 :c:func:`PyFloat_Unpack2`, :c:func:`PyFloat_Unpack4` and 2252 :c:func:`PyFloat_Unpack8`. 2253 (Contributed by Victor Stinner in :issue:`46906`.) 2254 2255* Add new functions to get frame object attributes: 2256 :c:func:`PyFrame_GetBuiltins`, :c:func:`PyFrame_GetGenerator`, 2257 :c:func:`PyFrame_GetGlobals`, :c:func:`PyFrame_GetLasti`. 2258 2259* Added two new functions to get and set the active exception instance: 2260 :c:func:`PyErr_GetHandledException` and :c:func:`PyErr_SetHandledException`. 2261 These are alternatives to :c:func:`PyErr_SetExcInfo()` and 2262 :c:func:`PyErr_GetExcInfo()` which work with the legacy 3-tuple 2263 representation of exceptions. 2264 (Contributed by Irit Katriel in :issue:`46343`.) 2265 2266* Added the :c:member:`PyConfig.safe_path` member. 2267 (Contributed by Victor Stinner in :gh:`57684`.) 2268 2269 2270.. _whatsnew311-c-api-porting: 2271 2272Porting to Python 3.11 2273---------------------- 2274 2275.. _whatsnew311-pep670: 2276 2277* Some macros have been converted to static inline functions to avoid 2278 `macro pitfalls <https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html>`_. 2279 The change should be mostly transparent to users, 2280 as the replacement functions will cast their arguments to the expected types 2281 to avoid compiler warnings due to static type checks. 2282 However, when the limited C API is set to >=3.11, 2283 these casts are not done, 2284 and callers will need to cast arguments to their expected types. 2285 See :pep:`670` for more details. 2286 (Contributed by Victor Stinner and Erlend E. Aasland in :gh:`89653`.) 2287 2288* :c:func:`PyErr_SetExcInfo()` no longer uses the ``type`` and ``traceback`` 2289 arguments, the interpreter now derives those values from the exception 2290 instance (the ``value`` argument). The function still steals references 2291 of all three arguments. 2292 (Contributed by Irit Katriel in :issue:`45711`.) 2293 2294* :c:func:`PyErr_GetExcInfo()` now derives the ``type`` and ``traceback`` 2295 fields of the result from the exception instance (the ``value`` field). 2296 (Contributed by Irit Katriel in :issue:`45711`.) 2297 2298* :c:struct:`_frozen` has a new ``is_package`` field to indicate whether 2299 or not the frozen module is a package. Previously, a negative value 2300 in the ``size`` field was the indicator. Now only non-negative values 2301 be used for ``size``. 2302 (Contributed by Kumar Aditya in :issue:`46608`.) 2303 2304* :c:func:`_PyFrameEvalFunction` now takes ``_PyInterpreterFrame*`` 2305 as its second parameter, instead of ``PyFrameObject*``. 2306 See :pep:`523` for more details of how to use this function pointer type. 2307 2308* :c:func:`PyCode_New` and :c:func:`PyCode_NewWithPosOnlyArgs` now take 2309 an additional ``exception_table`` argument. 2310 Using these functions should be avoided, if at all possible. 2311 To get a custom code object: create a code object using the compiler, 2312 then get a modified version with the ``replace`` method. 2313 2314* :c:type:`PyCodeObject` no longer has the ``co_code``, ``co_varnames``, 2315 ``co_cellvars`` and ``co_freevars`` fields. Instead, use 2316 :c:func:`PyCode_GetCode`, :c:func:`PyCode_GetVarnames`, 2317 :c:func:`PyCode_GetCellvars` and :c:func:`PyCode_GetFreevars` respectively 2318 to access them via the C API. 2319 (Contributed by Brandt Bucher in :issue:`46841` and Ken Jin in :gh:`92154` 2320 and :gh:`94936`.) 2321 2322* The old trashcan macros (``Py_TRASHCAN_SAFE_BEGIN``/``Py_TRASHCAN_SAFE_END``) 2323 are now deprecated. They should be replaced by the new macros 2324 ``Py_TRASHCAN_BEGIN`` and ``Py_TRASHCAN_END``. 2325 2326 A tp_dealloc function that has the old macros, such as:: 2327 2328 static void 2329 mytype_dealloc(mytype *p) 2330 { 2331 PyObject_GC_UnTrack(p); 2332 Py_TRASHCAN_SAFE_BEGIN(p); 2333 ... 2334 Py_TRASHCAN_SAFE_END 2335 } 2336 2337 should migrate to the new macros as follows:: 2338 2339 static void 2340 mytype_dealloc(mytype *p) 2341 { 2342 PyObject_GC_UnTrack(p); 2343 Py_TRASHCAN_BEGIN(p, mytype_dealloc) 2344 ... 2345 Py_TRASHCAN_END 2346 } 2347 2348 Note that ``Py_TRASHCAN_BEGIN`` has a second argument which 2349 should be the deallocation function it is in. 2350 2351 To support older Python versions in the same codebase, you 2352 can define the following macros and use them throughout 2353 the code (credit: these were copied from the ``mypy`` codebase):: 2354 2355 #if PY_VERSION_HEX >= 0x03080000 2356 # define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc) 2357 # define CPy_TRASHCAN_END(op) Py_TRASHCAN_END 2358 #else 2359 # define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_SAFE_BEGIN(op) 2360 # define CPy_TRASHCAN_END(op) Py_TRASHCAN_SAFE_END(op) 2361 #endif 2362 2363* The :c:func:`PyType_Ready` function now raises an error if a type is defined 2364 with the :const:`Py_TPFLAGS_HAVE_GC` flag set but has no traverse function 2365 (:c:member:`PyTypeObject.tp_traverse`). 2366 (Contributed by Victor Stinner in :issue:`44263`.) 2367 2368* Heap types with the :const:`Py_TPFLAGS_IMMUTABLETYPE` flag can now inherit 2369 the :pep:`590` vectorcall protocol. Previously, this was only possible for 2370 :ref:`static types <static-types>`. 2371 (Contributed by Erlend E. Aasland in :issue:`43908`) 2372 2373* Since :c:func:`Py_TYPE()` is changed to a inline static function, 2374 ``Py_TYPE(obj) = new_type`` must be replaced with 2375 ``Py_SET_TYPE(obj, new_type)``: see the :c:func:`Py_SET_TYPE()` function 2376 (available since Python 3.9). For backward compatibility, this macro can be 2377 used:: 2378 2379 #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE) 2380 static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) 2381 { ob->ob_type = type; } 2382 #define Py_SET_TYPE(ob, type) _Py_SET_TYPE((PyObject*)(ob), type) 2383 #endif 2384 2385 (Contributed by Victor Stinner in :issue:`39573`.) 2386 2387* Since :c:func:`Py_SIZE()` is changed to a inline static function, 2388 ``Py_SIZE(obj) = new_size`` must be replaced with 2389 ``Py_SET_SIZE(obj, new_size)``: see the :c:func:`Py_SET_SIZE()` function 2390 (available since Python 3.9). For backward compatibility, this macro can be 2391 used:: 2392 2393 #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE) 2394 static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) 2395 { ob->ob_size = size; } 2396 #define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size) 2397 #endif 2398 2399 (Contributed by Victor Stinner in :issue:`39573`.) 2400 2401* ``<Python.h>`` no longer includes the header files ``<stdlib.h>``, 2402 ``<stdio.h>``, ``<errno.h>`` and ``<string.h>`` when the ``Py_LIMITED_API`` 2403 macro is set to ``0x030b0000`` (Python 3.11) or higher. C extensions should 2404 explicitly include the header files after ``#include <Python.h>``. 2405 (Contributed by Victor Stinner in :issue:`45434`.) 2406 2407* The non-limited API files ``cellobject.h``, ``classobject.h``, ``code.h``, ``context.h``, 2408 ``funcobject.h``, ``genobject.h`` and ``longintrepr.h`` have been moved to 2409 the ``Include/cpython`` directory. Moreover, the ``eval.h`` header file was 2410 removed. These files must not be included directly, as they are already 2411 included in ``Python.h``: :ref:`Include Files <api-includes>`. If they have 2412 been included directly, consider including ``Python.h`` instead. 2413 (Contributed by Victor Stinner in :issue:`35134`.) 2414 2415* The :c:func:`PyUnicode_CHECK_INTERNED` macro has been excluded from the 2416 limited C API. It was never usable there, because it used internal structures 2417 which are not available in the limited C API. 2418 (Contributed by Victor Stinner in :issue:`46007`.) 2419 2420* The following frame functions and type are now directly available with 2421 ``#include <Python.h>``, it's no longer needed to add 2422 ``#include <frameobject.h>``: 2423 2424 * :c:func:`PyFrame_Check` 2425 * :c:func:`PyFrame_GetBack` 2426 * :c:func:`PyFrame_GetBuiltins` 2427 * :c:func:`PyFrame_GetGenerator` 2428 * :c:func:`PyFrame_GetGlobals` 2429 * :c:func:`PyFrame_GetLasti` 2430 * :c:func:`PyFrame_GetLocals` 2431 * :c:type:`PyFrame_Type` 2432 2433 (Contributed by Victor Stinner in :gh:`93937`.) 2434 2435.. _pyframeobject-3.11-hiding: 2436 2437* The :c:type:`PyFrameObject` structure members have been removed from the 2438 public C API. 2439 2440 While the documentation notes that the :c:type:`PyFrameObject` fields are 2441 subject to change at any time, they have been stable for a long time and were 2442 used in several popular extensions. 2443 2444 In Python 3.11, the frame struct was reorganized to allow performance 2445 optimizations. Some fields were removed entirely, as they were details of the 2446 old implementation. 2447 2448 :c:type:`PyFrameObject` fields: 2449 2450 * ``f_back``: use :c:func:`PyFrame_GetBack`. 2451 * ``f_blockstack``: removed. 2452 * ``f_builtins``: use :c:func:`PyFrame_GetBuiltins`. 2453 * ``f_code``: use :c:func:`PyFrame_GetCode`. 2454 * ``f_gen``: use :c:func:`PyFrame_GetGenerator`. 2455 * ``f_globals``: use :c:func:`PyFrame_GetGlobals`. 2456 * ``f_iblock``: removed. 2457 * ``f_lasti``: use :c:func:`PyFrame_GetLasti`. 2458 Code using ``f_lasti`` with ``PyCode_Addr2Line()`` should use 2459 :c:func:`PyFrame_GetLineNumber` instead; it may be faster. 2460 * ``f_lineno``: use :c:func:`PyFrame_GetLineNumber` 2461 * ``f_locals``: use :c:func:`PyFrame_GetLocals`. 2462 * ``f_stackdepth``: removed. 2463 * ``f_state``: no public API (renamed to ``f_frame.f_state``). 2464 * ``f_trace``: no public API. 2465 * ``f_trace_lines``: use ``PyObject_GetAttrString((PyObject*)frame, "f_trace_lines")``. 2466 * ``f_trace_opcodes``: use ``PyObject_GetAttrString((PyObject*)frame, "f_trace_opcodes")``. 2467 * ``f_localsplus``: no public API (renamed to ``f_frame.localsplus``). 2468 * ``f_valuestack``: removed. 2469 2470 The Python frame object is now created lazily. A side effect is that the 2471 ``f_back`` member must not be accessed directly, since its value is now also 2472 computed lazily. The :c:func:`PyFrame_GetBack` function must be called 2473 instead. 2474 2475 Debuggers that accessed the ``f_locals`` directly *must* call 2476 :c:func:`PyFrame_GetLocals` instead. They no longer need to call 2477 :c:func:`PyFrame_FastToLocalsWithError` or :c:func:`PyFrame_LocalsToFast`, 2478 in fact they should not call those functions. The necessary updating of the 2479 frame is now managed by the virtual machine. 2480 2481 Code defining ``PyFrame_GetCode()`` on Python 3.8 and older:: 2482 2483 #if PY_VERSION_HEX < 0x030900B1 2484 static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame) 2485 { 2486 Py_INCREF(frame->f_code); 2487 return frame->f_code; 2488 } 2489 #endif 2490 2491 Code defining ``PyFrame_GetBack()`` on Python 3.8 and older:: 2492 2493 #if PY_VERSION_HEX < 0x030900B1 2494 static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame) 2495 { 2496 Py_XINCREF(frame->f_back); 2497 return frame->f_back; 2498 } 2499 #endif 2500 2501 Or use the `pythoncapi_compat project 2502 <https://github.com/python/pythoncapi-compat>`__ to get these two 2503 functions on older Python versions. 2504 2505* Changes of the :c:type:`PyThreadState` structure members: 2506 2507 * ``frame``: removed, use :c:func:`PyThreadState_GetFrame` (function added 2508 to Python 3.9 by :issue:`40429`). 2509 Warning: the function returns a :term:`strong reference`, need to call 2510 :c:func:`Py_XDECREF`. 2511 * ``tracing``: changed, use :c:func:`PyThreadState_EnterTracing` 2512 and :c:func:`PyThreadState_LeaveTracing` 2513 (functions added to Python 3.11 by :issue:`43760`). 2514 * ``recursion_depth``: removed, 2515 use ``(tstate->recursion_limit - tstate->recursion_remaining)`` instead. 2516 * ``stackcheck_counter``: removed. 2517 2518 Code defining ``PyThreadState_GetFrame()`` on Python 3.8 and older:: 2519 2520 #if PY_VERSION_HEX < 0x030900B1 2521 static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate) 2522 { 2523 Py_XINCREF(tstate->frame); 2524 return tstate->frame; 2525 } 2526 #endif 2527 2528 Code defining ``PyThreadState_EnterTracing()`` and 2529 ``PyThreadState_LeaveTracing()`` on Python 3.10 and older:: 2530 2531 #if PY_VERSION_HEX < 0x030B00A2 2532 static inline void PyThreadState_EnterTracing(PyThreadState *tstate) 2533 { 2534 tstate->tracing++; 2535 #if PY_VERSION_HEX >= 0x030A00A1 2536 tstate->cframe->use_tracing = 0; 2537 #else 2538 tstate->use_tracing = 0; 2539 #endif 2540 } 2541 2542 static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) 2543 { 2544 int use_tracing = (tstate->c_tracefunc != NULL || tstate->c_profilefunc != NULL); 2545 tstate->tracing--; 2546 #if PY_VERSION_HEX >= 0x030A00A1 2547 tstate->cframe->use_tracing = use_tracing; 2548 #else 2549 tstate->use_tracing = use_tracing; 2550 #endif 2551 } 2552 #endif 2553 2554 Or use `the pythoncapi-compat project 2555 <https://github.com/python/pythoncapi-compat>`__ to get these functions 2556 on old Python functions. 2557 2558* Distributors are encouraged to build Python with the optimized Blake2 2559 library `libb2`_. 2560 2561* The :c:member:`PyConfig.module_search_paths_set` field must now be set to 1 for 2562 initialization to use :c:member:`PyConfig.module_search_paths` to initialize 2563 :data:`sys.path`. Otherwise, initialization will recalculate the path and replace 2564 any values added to ``module_search_paths``. 2565 2566* :c:func:`PyConfig_Read` no longer calculates the initial search path, and will not 2567 fill any values into :c:member:`PyConfig.module_search_paths`. To calculate default 2568 paths and then modify them, finish initialization and use :c:func:`PySys_GetObject` 2569 to retrieve :data:`sys.path` as a Python list object and modify it directly. 2570 2571 2572.. _whatsnew311-c-api-deprecated: 2573 2574Deprecated 2575---------- 2576 2577* Deprecate the following functions to configure the Python initialization: 2578 2579 * :c:func:`PySys_AddWarnOptionUnicode` 2580 * :c:func:`PySys_AddWarnOption` 2581 * :c:func:`PySys_AddXOption` 2582 * :c:func:`PySys_HasWarnOptions` 2583 * :c:func:`PySys_SetArgvEx` 2584 * :c:func:`PySys_SetArgv` 2585 * :c:func:`PySys_SetPath` 2586 * :c:func:`Py_SetPath` 2587 * :c:func:`Py_SetProgramName` 2588 * :c:func:`Py_SetPythonHome` 2589 * :c:func:`Py_SetStandardStreamEncoding` 2590 * :c:func:`_Py_SetProgramFullPath` 2591 2592 Use the new :c:type:`PyConfig` API of the :ref:`Python Initialization Configuration 2593 <init-config>` instead (:pep:`587`). 2594 (Contributed by Victor Stinner in :gh:`88279`.) 2595 2596* Deprecate the ``ob_shash`` member of the :c:type:`PyBytesObject`. Use :c:func:`PyObject_Hash` instead. 2597 (Contributed by Inada Naoki in :issue:`46864`.) 2598 2599 2600.. _whatsnew311-c-api-pending-removal: 2601 2602Pending Removal in Python 3.12 2603------------------------------ 2604 2605The following C APIs have been deprecated in earlier Python releases, 2606and will be removed in Python 3.12. 2607 2608* :c:func:`PyUnicode_AS_DATA` 2609* :c:func:`PyUnicode_AS_UNICODE` 2610* :c:func:`PyUnicode_AsUnicodeAndSize` 2611* :c:func:`PyUnicode_AsUnicode` 2612* :c:func:`PyUnicode_FromUnicode` 2613* :c:func:`PyUnicode_GET_DATA_SIZE` 2614* :c:func:`PyUnicode_GET_SIZE` 2615* :c:func:`PyUnicode_GetSize` 2616* :c:func:`PyUnicode_IS_COMPACT` 2617* :c:func:`PyUnicode_IS_READY` 2618* :c:func:`PyUnicode_READY` 2619* :c:func:`Py_UNICODE_WSTR_LENGTH` 2620* :c:func:`_PyUnicode_AsUnicode` 2621* :c:macro:`PyUnicode_WCHAR_KIND` 2622* :c:type:`PyUnicodeObject` 2623* :c:func:`PyUnicode_InternImmortal()` 2624 2625 2626.. _whatsnew311-c-api-removed: 2627 2628Removed 2629------- 2630 2631* :c:func:`PyFrame_BlockSetup` and :c:func:`PyFrame_BlockPop` have been 2632 removed. 2633 (Contributed by Mark Shannon in :issue:`40222`.) 2634 2635* Remove the following math macros using the ``errno`` variable: 2636 2637 * ``Py_ADJUST_ERANGE1()`` 2638 * ``Py_ADJUST_ERANGE2()`` 2639 * ``Py_OVERFLOWED()`` 2640 * ``Py_SET_ERANGE_IF_OVERFLOW()`` 2641 * ``Py_SET_ERRNO_ON_MATH_ERROR()`` 2642 2643 (Contributed by Victor Stinner in :issue:`45412`.) 2644 2645* Remove ``Py_UNICODE_COPY()`` and ``Py_UNICODE_FILL()`` macros, deprecated 2646 since Python 3.3. Use ``PyUnicode_CopyCharacters()`` or ``memcpy()`` 2647 (``wchar_t*`` string), and ``PyUnicode_Fill()`` functions instead. 2648 (Contributed by Victor Stinner in :issue:`41123`.) 2649 2650* Remove the ``pystrhex.h`` header file. It only contains private functions. 2651 C extensions should only include the main ``<Python.h>`` header file. 2652 (Contributed by Victor Stinner in :issue:`45434`.) 2653 2654* Remove the ``Py_FORCE_DOUBLE()`` macro. It was used by the 2655 ``Py_IS_INFINITY()`` macro. 2656 (Contributed by Victor Stinner in :issue:`45440`.) 2657 2658* The following items are no longer available when :c:macro:`Py_LIMITED_API` 2659 is defined: 2660 2661 * :c:func:`PyMarshal_WriteLongToFile` 2662 * :c:func:`PyMarshal_WriteObjectToFile` 2663 * :c:func:`PyMarshal_ReadObjectFromString` 2664 * :c:func:`PyMarshal_WriteObjectToString` 2665 * the ``Py_MARSHAL_VERSION`` macro 2666 2667 These are not part of the :ref:`limited API <stable-abi-list>`. 2668 2669 (Contributed by Victor Stinner in :issue:`45474`.) 2670 2671* Exclude :c:func:`PyWeakref_GET_OBJECT` from the limited C API. It never 2672 worked since the :c:type:`PyWeakReference` structure is opaque in the 2673 limited C API. 2674 (Contributed by Victor Stinner in :issue:`35134`.) 2675 2676* Remove the ``PyHeapType_GET_MEMBERS()`` macro. It was exposed in the 2677 public C API by mistake, it must only be used by Python internally. 2678 Use the ``PyTypeObject.tp_members`` member instead. 2679 (Contributed by Victor Stinner in :issue:`40170`.) 2680 2681* Remove the ``HAVE_PY_SET_53BIT_PRECISION`` macro (moved to the internal C 2682 API). 2683 (Contributed by Victor Stinner in :issue:`45412`.) 2684 2685.. _whatsnew311-pep624: 2686 2687* Remove the :c:type:`Py_UNICODE` encoder APIs, 2688 as they have been deprecated since Python 3.3, 2689 are little used 2690 and are inefficient relative to the recommended alternatives. 2691 2692 The removed functions are: 2693 2694 * :func:`!PyUnicode_Encode` 2695 * :func:`!PyUnicode_EncodeASCII` 2696 * :func:`!PyUnicode_EncodeLatin1` 2697 * :func:`!PyUnicode_EncodeUTF7` 2698 * :func:`!PyUnicode_EncodeUTF8` 2699 * :func:`!PyUnicode_EncodeUTF16` 2700 * :func:`!PyUnicode_EncodeUTF32` 2701 * :func:`!PyUnicode_EncodeUnicodeEscape` 2702 * :func:`!PyUnicode_EncodeRawUnicodeEscape` 2703 * :func:`!PyUnicode_EncodeCharmap` 2704 * :func:`!PyUnicode_TranslateCharmap` 2705 * :func:`!PyUnicode_EncodeDecimal` 2706 * :func:`!PyUnicode_TransformDecimalToASCII` 2707 2708 See :pep:`624` for details and 2709 :pep:`migration guidance <624#alternative-apis>`. 2710 (Contributed by Inada Naoki in :issue:`44029`.) 2711 2712 2713Notable Changes in 3.11.4 2714========================= 2715 2716tarfile 2717------- 2718 2719* The extraction methods in :mod:`tarfile`, and :func:`shutil.unpack_archive`, 2720 have a new a *filter* argument that allows limiting tar features than may be 2721 surprising or dangerous, such as creating files outside the destination 2722 directory. 2723 See :ref:`tarfile-extraction-filter` for details. 2724 In Python 3.12, use without the *filter* argument will show a 2725 :exc:`DeprecationWarning`. 2726 In Python 3.14, the default will switch to ``'data'``. 2727 (Contributed by Petr Viktorin in :pep:`706`.) 2728 2729.. _libb2: https://www.blake2.net/ 2730