-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy path3.11.rst
More file actions
2744 lines (2042 loc) · 108 KB
/
3.11.rst
File metadata and controls
2744 lines (2042 loc) · 108 KB
Edit and raw actions
OlderNewer
1
****************************
2
What's New In Python 3.11
3
****************************
4
5
:Editor: Pablo Galindo Salgado
6
7
.. Rules for maintenance:
8
9
* Anyone can add text to this document. Do not spend very much time
10
on the wording of your changes, because your text will probably
11
get rewritten to some degree.
12
13
* The maintainer will go through Misc/NEWS periodically and add
14
changes; it's therefore more important to add your changes to
15
Misc/NEWS than to this file.
16
17
* This is not a complete list of every single change; completeness
18
is the purpose of Misc/NEWS. Some changes I consider too small
19
or esoteric to include. If such a change is added to the text,
20
I'll just remove it. (This is another reason you shouldn't spend
21
too much time on writing your addition.)
22
23
* If you want to draw your new text to the attention of the
24
maintainer, add 'XXX' to the beginning of the paragraph or
25
section.
26
27
* It's OK to just add a fragmentary note about a change. For
28
example: "XXX Describe the transmogrify() function added to the
29
socket module." The maintainer will research the change and
30
write the necessary text.
31
32
* You can comment out your additions if you like, but it's not
33
necessary (especially when a final release is some months away).
34
35
* Credit the author of a patch or bugfix. Just the name is
36
sufficient; the e-mail address isn't necessary.
37
38
* It's helpful to add the bug/patch number as a comment:
39
40
XXX Describe the transmogrify() function added to the socket
41
module.
42
(Contributed by P.Y. Developer in :issue:`12345`.)
43
44
This saves the maintainer the effort of going through the Mercurial log
45
when researching a change.
46
47
This article explains the new features in Python 3.11, compared to 3.10.
48
Python 3.11 was released on October 24, 2022.
49
For full details, see the :ref:`changelog <changelog>`.
50
51
52
.. _whatsnew311-summary:
53
54
Summary -- Release highlights
55
=============================
56
57
.. This section singles out the most important changes in Python 3.11.
58
Brevity is key.
59
60
* Python 3.11 is between 10-60% faster than Python 3.10.
61
On average, we measured a 1.25x speedup on the standard benchmark suite.
62
See :ref:`whatsnew311-faster-cpython` for details.
63
64
.. PEP-sized items next.
65
66
New syntax features:
67
68
* :ref:`whatsnew311-pep654`
69
70
New built-in features:
71
72
* :ref:`whatsnew311-pep678`
73
74
New standard library modules:
75
76
* :pep:`680`: :mod:`tomllib` —
77
Support for parsing `TOML <https://toml.io/>`_ in the Standard Library
78
79
Interpreter improvements:
80
81
* :ref:`whatsnew311-pep657`
82
* New :option:`-P` command line option and :envvar:`PYTHONSAFEPATH` environment
83
variable to :ref:`disable automatically prepending potentially unsafe paths
84
<whatsnew311-pythonsafepath>` to :data:`sys.path`
85
86
New typing features:
87
88
* :ref:`whatsnew311-pep646`
89
* :ref:`whatsnew311-pep655`
90
* :ref:`whatsnew311-pep673`
91
* :ref:`whatsnew311-pep675`
92
* :ref:`whatsnew311-pep681`
93
94
Important deprecations, removals and restrictions:
95
96
* :pep:`594`:
97
:ref:`Many legacy standard library modules have been deprecated
98
<whatsnew311-pep594>` and will be removed in Python 3.13
99
* :pep:`624`:
100
:ref:`Py_UNICODE encoder APIs have been removed <whatsnew311-pep624>`
101
* :pep:`670`:
102
:ref:`Macros converted to static inline functions <whatsnew311-pep670>`
103
104
105
.. _whatsnew311-features:
106
107
New Features
108
============
109
110
.. _whatsnew311-pep657:
111
112
PEP 657: Fine-grained error locations in tracebacks
113
---------------------------------------------------
114
115
When printing tracebacks, the interpreter will now point to the exact expression
116
that caused the error, instead of just the line. For example:
117
118
.. code-block:: python
119
120
Traceback (most recent call last):
121
File "distance.py", line 11, in <module>
122
print(manhattan_distance(p1, p2))
123
^^^^^^^^^^^^^^^^^^^^^^^^^^
124
File "distance.py", line 6, in manhattan_distance
125
return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
126
^^^^^^^^^
127
AttributeError: 'NoneType' object has no attribute 'x'
128
129
Previous versions of the interpreter would point to just the line, making it
130
ambiguous which object was ``None``. These enhanced errors can also be helpful
131
when dealing with deeply nested :class:`dict` objects and multiple function calls:
132
133
.. code-block:: python
134
135
Traceback (most recent call last):
136
File "query.py", line 37, in <module>
137
magic_arithmetic('foo')
138
File "query.py", line 18, in magic_arithmetic
139
return add_counts(x) / 25
140
^^^^^^^^^^^^^
141
File "query.py", line 24, in add_counts
142
return 25 + query_user(user1) + query_user(user2)
143
^^^^^^^^^^^^^^^^^
144
File "query.py", line 32, in query_user
145
return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
146
~~~~~~~~~~~~~~~~~~^^^^^
147
TypeError: 'NoneType' object is not subscriptable
148
149
As well as complex arithmetic expressions:
150
151
.. code-block:: python
152
153
Traceback (most recent call last):
154
File "calculation.py", line 54, in <module>
155
result = (x / y / z) * (a / b / c)
156
~~~~~~^~~
157
ZeroDivisionError: division by zero
158
159
Additionally, the information used by the enhanced traceback feature
160
is made available via a general API, that can be used to correlate
161
:term:`bytecode` :ref:`instructions <bytecodes>` with source code location.
162
This information can be retrieved using:
163
164
- The :meth:`codeobject.co_positions` method in Python.
165
- The :c:func:`PyCode_Addr2Location` function in the C API.
166
167
See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya
168
and Ammar Askar in :issue:`43950`.)
169
170
.. note::
171
This feature requires storing column positions in :ref:`codeobjects`,
172
which may result in a small increase in interpreter memory usage
173
and disk usage for compiled Python files.
174
To avoid storing the extra information
175
and deactivate printing the extra traceback information,
176
use the :option:`-X no_debug_ranges <-X>` command line option
177
or the :envvar:`PYTHONNODEBUGRANGES` environment variable.
178
179
180
.. _whatsnew311-pep654:
181
182
PEP 654: Exception Groups and ``except*``
183
-----------------------------------------
184
185
:pep:`654` introduces language features that enable a program
186
to raise and handle multiple unrelated exceptions simultaneously.
187
The builtin types :exc:`ExceptionGroup` and :exc:`BaseExceptionGroup`
188
make it possible to group exceptions and raise them together,
189
and the new :keyword:`except* <except_star>` syntax generalizes
190
:keyword:`except` to match subgroups of exception groups.
191
192
See :pep:`654` for more details.
193
194
(Contributed by Irit Katriel in :issue:`45292`. PEP written by
195
Irit Katriel, Yury Selivanov and Guido van Rossum.)
196
197
198
.. _whatsnew311-pep678:
199
200
PEP 678: Exceptions can be enriched with notes
201
----------------------------------------------
202
203
The :meth:`~BaseException.add_note` method is added to :exc:`BaseException`.
204
It can be used to enrich exceptions with context information
205
that is not available at the time when the exception is raised.
206
The added notes appear in the default traceback.
207
208
See :pep:`678` for more details.
209
210
(Contributed by Irit Katriel in :issue:`45607`.
211
PEP written by Zac Hatfield-Dodds.)
212
213
214
.. _whatsnew311-windows-launcher:
215
216
Windows ``py.exe`` launcher improvements
217
----------------------------------------
218
219
The copy of the :ref:`launcher` included with Python 3.11 has been significantly
220
updated. It now supports company/tag syntax as defined in :pep:`514` using the
221
:samp:`-V:{<company>}/{<tag>}` argument instead of the limited :samp:`-{<major>}.{<minor>}`.
222
This allows launching distributions other than ``PythonCore``,
223
the one hosted on `python.org <https://www.python.org>`_.
224
225
When using ``-V:`` selectors, either company or tag can be omitted, but all
226
installs will be searched. For example, ``-V:OtherPython/`` will select the
227
"best" tag registered for ``OtherPython``, while ``-V:3.11`` or ``-V:/3.11``
228
will select the "best" distribution with tag ``3.11``.
229
230
When using the legacy :samp:`-{<major>}`, :samp:`-{<major>}.{<minor>}`,
231
:samp:`-{<major>}-{<bitness>}` or :samp:`-{<major>}.{<minor>}-{<bitness>}` arguments,
232
all existing behaviour should be preserved from past versions,
233
and only releases from ``PythonCore`` will be selected.
234
However, the ``-64`` suffix now implies "not 32-bit" (not necessarily x86-64),
235
as there are multiple supported 64-bit platforms.
236
32-bit runtimes are detected by checking the runtime's tag for a ``-32`` suffix.
237
All releases of Python since 3.5 have included this in their 32-bit builds.
238
239
240
.. _new-feat-related-type-hints-311:
241
.. _whatsnew311-typing-features:
242
243
New Features Related to Type Hints
244
==================================
245
246
This section covers major changes affecting :pep:`484` type hints and
247
the :mod:`typing` module.
248
249
250
.. _whatsnew311-pep646:
251
252
PEP 646: Variadic generics
253
--------------------------
254
255
:pep:`484` previously introduced :data:`~typing.TypeVar`, enabling creation
256
of generics parameterised with a single type. :pep:`646` adds
257
:data:`~typing.TypeVarTuple`, enabling parameterisation
258
with an *arbitrary* number of types. In other words,
259
a :data:`~typing.TypeVarTuple` is a *variadic* type variable,
260
enabling *variadic* generics.
261
262
This enables a wide variety of use cases.
263
In particular, it allows the type of array-like structures
264
in numerical computing libraries such as NumPy and TensorFlow to be
265
parameterised with the array *shape*. Static type checkers will now
266
be able to catch shape-related bugs in code that uses these libraries.
267
268
See :pep:`646` for more details.
269
270
(Contributed by Matthew Rahtz in :issue:`43224`, with contributions by
271
Serhiy Storchaka and Jelle Zijlstra. PEP written by Mark Mendoza, Matthew
272
Rahtz, Pradeep Kumar Srinivasan, and Vincent Siles.)
273
274
275
.. _whatsnew311-pep655:
276
277
PEP 655: Marking individual ``TypedDict`` items as required or not-required
278
---------------------------------------------------------------------------
279
280
:data:`~typing.Required` and :data:`~typing.NotRequired` provide a
281
straightforward way to mark whether individual items in a
282
:class:`~typing.TypedDict` must be present. Previously, this was only possible
283
using inheritance.
284
285
All fields are still required by default,
286
unless the *total* parameter is set to ``False``,
287
in which case all fields are still not-required by default.
288
For example, the following specifies a :class:`!TypedDict`
289
with one required and one not-required key::
290
291
class Movie(TypedDict):
292
title: str
293
year: NotRequired[int]
294
295
m1: Movie = {"title": "Black Panther", "year": 2018} # OK
296
m2: Movie = {"title": "Star Wars"} # OK (year is not required)
297
m3: Movie = {"year": 2022} # ERROR (missing required field title)
298
299
The following definition is equivalent::
300
301
class Movie(TypedDict, total=False):
302
title: Required[str]
303
year: int
304
305
See :pep:`655` for more details.
306
307
(Contributed by David Foster and Jelle Zijlstra in :issue:`47087`. PEP
308
written by David Foster.)
309
310
311
.. _whatsnew311-pep673:
312
313
PEP 673: ``Self`` type
314
----------------------
315
316
The new :data:`~typing.Self` annotation provides a simple and intuitive
317
way to annotate methods that return an instance of their class. This
318
behaves the same as the :class:`~typing.TypeVar`-based approach
319
:pep:`specified in PEP 484 <484#annotating-instance-and-class-methods>`,
320
but is more concise and easier to follow.
321
322
Common use cases include alternative constructors provided as
323
:func:`classmethod <classmethod>`\s,
324
and :meth:`~object.__enter__` methods that return ``self``::
325
326
class MyLock:
327
def __enter__(self) -> Self:
328
self.lock()
329
return self
330
331
...
332
333
class MyInt:
334
@classmethod
335
def fromhex(cls, s: str) -> Self:
336
return cls(int(s, 16))
337
338
...
339
340
:data:`~typing.Self` can also be used to annotate method parameters
341
or attributes of the same type as their enclosing class.
342
343
See :pep:`673` for more details.
344
345
(Contributed by James Hilton-Balfe in :issue:`46534`. PEP written by
346
Pradeep Kumar Srinivasan and James Hilton-Balfe.)
347
348
349
.. _whatsnew311-pep675:
350
351
PEP 675: Arbitrary literal string type
352
--------------------------------------
353
354
The new :data:`~typing.LiteralString` annotation may be used to indicate
355
that a function parameter can be of any literal string type. This allows
356
a function to accept arbitrary literal string types, as well as strings
357
created from other literal strings. Type checkers can then
358
enforce that sensitive functions, such as those that execute SQL
359
statements or shell commands, are called only with static arguments,
360
providing protection against injection attacks.
361
362
For example, a SQL query function could be annotated as follows::
363
364
def run_query(sql: LiteralString) -> ...
365
...
366
367
def caller(
368
arbitrary_string: str,
369
query_string: LiteralString,
370
table_name: LiteralString,
371
) -> None:
372
run_query("SELECT * FROM students") # ok
373
run_query(query_string) # ok
374
run_query("SELECT * FROM " + table_name) # ok
375
run_query(arbitrary_string) # type checker error
376
run_query( # type checker error
377
f"SELECT * FROM students WHERE name = {arbitrary_string}"
378
)
379
380
See :pep:`675` for more details.
381
382
(Contributed by Jelle Zijlstra in :issue:`47088`. PEP written by Pradeep
383
Kumar Srinivasan and Graham Bleaney.)
384
385
386
.. _whatsnew311-pep681:
387
388
PEP 681: Data class transforms
389
------------------------------
390
391
:data:`~typing.dataclass_transform` may be used to
392
decorate a class, metaclass, or a function that is itself a decorator.
393
The presence of ``@dataclass_transform()`` tells a static type checker that the
394
decorated object performs runtime "magic" that transforms a class,
395
giving it :func:`dataclass <dataclasses.dataclass>`-like behaviors.
396
397
For example::
398
399
# The create_model decorator is defined by a library.
400
@typing.dataclass_transform()
401
def create_model(cls: Type[T]) -> Type[T]:
402
cls.__init__ = ...
403
cls.__eq__ = ...
404
cls.__ne__ = ...
405
return cls
406
407
# The create_model decorator can now be used to create new model classes:
408
@create_model
409
class CustomerModel:
410
id: int
411
name: str
412
413
c = CustomerModel(id=327, name="Eric Idle")
414
415
See :pep:`681` for more details.
416
417
(Contributed by Jelle Zijlstra in :gh:`91860`. PEP written by
418
Erik De Bonte and Eric Traut.)
419
420
421
.. _whatsnew311-pep563-deferred:
422
423
PEP 563 may not be the future
424
-----------------------------
425
426
:pep:`563` Postponed Evaluation of Annotations
427
(the ``from __future__ import annotations`` :ref:`future statement <future>`)
428
that was originally planned for release in Python 3.10
429
has been put on hold indefinitely.
430
See `this message from the Steering Council <https://mail.python.org/archives/list/[email protected]/message/VIZEBX5EYMSYIJNDBF6DMUMZOCWHARSO/>`__
431
for more information.
432
433
434
.. _whatsnew311-other-lang-changes:
435
436
Other Language Changes
437
======================
438
439
* Starred unpacking expressions can now be used in :keyword:`for` statements.
440
(See :issue:`46725` for more details.)
441
442
* Asynchronous :ref:`comprehensions <comprehensions>` are now allowed
443
inside comprehensions in :ref:`asynchronous functions <async def>`.
444
Outer comprehensions implicitly become asynchronous in this case.
445
(Contributed by Serhiy Storchaka in :issue:`33346`.)
446
447
* A :exc:`TypeError` is now raised instead of an :exc:`AttributeError` in
448
:keyword:`with` statements and :meth:`contextlib.ExitStack.enter_context`
449
for objects that do not support the :term:`context manager` protocol,
450
and in :keyword:`async with` statements and
451
:meth:`contextlib.AsyncExitStack.enter_async_context`
452
for objects not supporting the :term:`asynchronous context manager` protocol.
453
(Contributed by Serhiy Storchaka in :issue:`12022` and :issue:`44471`.)
454
455
* Added :meth:`object.__getstate__`, which provides the default
456
implementation of the :meth:`!__getstate__` method. :mod:`copy`\ing
457
and :mod:`pickle`\ing instances of subclasses of builtin types
458
:class:`bytearray`, :class:`set`, :class:`frozenset`,
459
:class:`collections.OrderedDict`, :class:`collections.deque`,
460
:class:`weakref.WeakSet`, and :class:`datetime.tzinfo` now copies and
461
pickles instance attributes implemented as :term:`slots <__slots__>`.
462
This change has an unintended side effect: It trips up a small minority
463
of existing Python projects not expecting :meth:`object.__getstate__` to
464
exist. See the later comments on :gh:`70766` for discussions of what
465
workarounds such code may need.
466
(Contributed by Serhiy Storchaka in :issue:`26579`.)
467
468
.. _whatsnew311-pythonsafepath:
469
470
* Added a :option:`-P` command line option
471
and a :envvar:`PYTHONSAFEPATH` environment variable,
472
which disable the automatic prepending to :data:`sys.path`
473
of the script's directory when running a script,
474
or the current directory when using :option:`-c` and :option:`-m`.
475
This ensures only stdlib and installed modules
476
are picked up by :keyword:`import`,
477
and avoids unintentionally or maliciously shadowing modules
478
with those in a local (and typically user-writable) directory.
479
(Contributed by Victor Stinner in :gh:`57684`.)
480
481
* A ``"z"`` option was added to the :ref:`formatspec` that
482
coerces negative to positive zero after rounding to the format precision.
483
See :pep:`682` for more details.
484
(Contributed by John Belmonte in :gh:`90153`.)
485
486
* Bytes are no longer accepted on :data:`sys.path`. Support broke sometime
487
between Python 3.2 and 3.6, with no one noticing until after Python 3.10.0
488
was released. In addition, bringing back support would be problematic due to
489
interactions between :option:`-b` and :data:`sys.path_importer_cache` when
490
there is a mixture of :class:`str` and :class:`bytes` keys.
491
(Contributed by Thomas Grainger in :gh:`91181`.)
492
493
494
.. _whatsnew311-other-implementation-changes:
495
496
Other CPython Implementation Changes
497
====================================
498
499
* The special methods :meth:`~object.__complex__` for :class:`complex`
500
and :meth:`~object.__bytes__` for :class:`bytes` are implemented to support
501
the :class:`typing.SupportsComplex` and :class:`typing.SupportsBytes` protocols.
502
(Contributed by Mark Dickinson and Donghee Na in :issue:`24234`.)
503
504
* ``siphash13`` is added as a new internal hashing algorithm.
505
It has similar security properties as ``siphash24``,
506
but it is slightly faster for long inputs.
507
:class:`str`, :class:`bytes`, and some other types
508
now use it as the default algorithm for :func:`hash`.
509
:pep:`552` :ref:`hash-based .pyc files <pyc-invalidation>`
510
now use ``siphash13`` too.
511
(Contributed by Inada Naoki in :issue:`29410`.)
512
513
* When an active exception is re-raised by a :keyword:`raise` statement with no parameters,
514
the traceback attached to this exception is now always ``sys.exc_info()[1].__traceback__``.
515
This means that changes made to the traceback in the current :keyword:`except` clause are
516
reflected in the re-raised exception.
517
(Contributed by Irit Katriel in :issue:`45711`.)
518
519
* The interpreter state's representation of handled exceptions
520
(aka ``exc_info`` or ``_PyErr_StackItem``)
521
now only has the ``exc_value`` field; ``exc_type`` and ``exc_traceback``
522
have been removed, as they can be derived from ``exc_value``.
523
(Contributed by Irit Katriel in :issue:`45711`.)
524
525
* A new :ref:`command line option <install-quiet-option>`, ``AppendPath``,
526
has been added for the Windows installer.
527
It behaves similarly to ``PrependPath``,
528
but appends the install and scripts directories instead of prepending them.
529
(Contributed by Bastian Neuburger in :issue:`44934`.)
530
531
* The :c:member:`PyConfig.module_search_paths_set` field must now be set to ``1`` for
532
initialization to use :c:member:`PyConfig.module_search_paths` to initialize
533
:data:`sys.path`. Otherwise, initialization will recalculate the path and replace
534
any values added to ``module_search_paths``.
535
536
* The output of the :option:`--help` option now fits in 50 lines/80 columns.
537
Information about :ref:`Python environment variables <using-on-envvars>`
538
and :option:`-X` options is now available using the respective
539
:option:`--help-env` and :option:`--help-xoptions` flags,
540
and with the new :option:`--help-all`.
541
(Contributed by Éric Araujo in :issue:`46142`.)
542
543
* Converting between :class:`int` and :class:`str` in bases other than 2
544
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
545
now raises a :exc:`ValueError` if the number of digits in string form is
546
above a limit to avoid potential denial of service attacks due to the
547
algorithmic complexity. This is a mitigation for :cve:`2020-10735`.
548
This limit can be configured or disabled by environment variable, command
549
line flag, or :mod:`sys` APIs. See the :ref:`integer string conversion
550
length limitation <int_max_str_digits>` documentation. The default limit
551
is 4300 digits in string form.
552
553
554
.. _whatsnew311-new-modules:
555
556
New Modules
557
===========
558
559
* :mod:`tomllib`: For parsing `TOML <https://toml.io/>`_.
560
See :pep:`680` for more details.
561
(Contributed by Taneli Hukkinen in :issue:`40059`.)
562
563
* :mod:`wsgiref.types`:
564
:pep:`WSGI <3333>`-specific types for static type checking.
565
(Contributed by Sebastian Rittau in :issue:`42012`.)
566
567
568
.. _whatsnew311-improved-modules:
569
570
Improved Modules
571
================
572
573
.. _whatsnew311-asyncio:
574
575
asyncio
576
-------
577
578
* Added the :class:`~asyncio.TaskGroup` class,
579
an :ref:`asynchronous context manager <async-context-managers>`
580
holding a group of tasks that will wait for all of them upon exit.
581
For new code this is recommended over using
582
:func:`~asyncio.create_task` and :func:`~asyncio.gather` directly.
583
(Contributed by Yury Selivanov and others in :gh:`90908`.)
584
585
* Added :func:`~asyncio.timeout`, an asynchronous context manager for
586
setting a timeout on asynchronous operations. For new code this is
587
recommended over using :func:`~asyncio.wait_for` directly.
588
(Contributed by Andrew Svetlov in :gh:`90927`.)
589
590
* Added the :class:`~asyncio.Runner` class, which exposes the machinery
591
used by :func:`~asyncio.run`.
592
(Contributed by Andrew Svetlov in :gh:`91218`.)
593
594
* Added the :class:`~asyncio.Barrier` class to the synchronization
595
primitives in the asyncio library, and the related
596
:exc:`~asyncio.BrokenBarrierError` exception.
597
(Contributed by Yves Duprat and Andrew Svetlov in :gh:`87518`.)
598
599
* Added keyword argument *all_errors* to :meth:`asyncio.loop.create_connection`
600
so that multiple connection errors can be raised as an :exc:`ExceptionGroup`.
601
602
* Added the :meth:`asyncio.StreamWriter.start_tls` method for
603
upgrading existing stream-based connections to TLS.
604
(Contributed by Ian Good in :issue:`34975`.)
605
606
* Added raw datagram socket functions to the event loop:
607
:meth:`~asyncio.loop.sock_sendto`,
608
:meth:`~asyncio.loop.sock_recvfrom` and
609
:meth:`~asyncio.loop.sock_recvfrom_into`.
610
These have implementations in :class:`~asyncio.SelectorEventLoop` and
611
:class:`~asyncio.ProactorEventLoop`.
612
(Contributed by Alex Grönholm in :issue:`46805`.)
613
614
* Added :meth:`~asyncio.Task.cancelling` and
615
:meth:`~asyncio.Task.uncancel` methods to :class:`~asyncio.Task`.
616
These are primarily intended for internal use,
617
notably by :class:`~asyncio.TaskGroup`.
618
619
620
.. _whatsnew311-contextlib:
621
622
contextlib
623
----------
624
625
* Added non parallel-safe :func:`~contextlib.chdir` context manager to change
626
the current working directory and then restore it on exit. Simple wrapper
627
around :func:`~os.chdir`. (Contributed by Filipe Laíns in :issue:`25625`)
628
629
630
.. _whatsnew311-dataclasses:
631
632
dataclasses
633
-----------
634
635
* Change field default mutability check, allowing only defaults which are
636
:term:`hashable` instead of any object which is not an instance of
637
:class:`dict`, :class:`list` or :class:`set`. (Contributed by Eric V. Smith in
638
:issue:`44674`.)
639
640
641
.. _whatsnew311-datetime:
642
643
datetime
644
--------
645
646
* Add :const:`datetime.UTC`, a convenience alias for
647
:attr:`datetime.timezone.utc`. (Contributed by Kabir Kwatra in :gh:`91973`.)
648
649
* :meth:`datetime.date.fromisoformat`, :meth:`datetime.time.fromisoformat` and
650
:meth:`datetime.datetime.fromisoformat` can now be used to parse most ISO 8601
651
formats (barring only those that support fractional hours and minutes).
652
(Contributed by Paul Ganssle in :gh:`80010`.)
653
654
655
.. _whatsnew311-enum:
656
657
enum
658
----
659
660
* Renamed :class:`!EnumMeta` to :class:`~enum.EnumType`
661
(:class:`!EnumMeta` kept as an alias).
662
663
* Added :class:`~enum.StrEnum`,
664
with members that can be used as (and must be) strings.
665
666
* Added :class:`~enum.ReprEnum`,
667
which only modifies the :meth:`~object.__repr__` of members
668
while returning their literal values (rather than names)
669
for :meth:`~object.__str__` and :meth:`~object.__format__`
670
(used by :func:`str`, :func:`format` and :term:`f-string`\s).
671
672
* Changed :meth:`Enum.__format__() <enum.Enum.__format__>` (the default for
673
:func:`format`, :meth:`str.format` and :term:`f-string`\s) to always produce
674
the same result as :meth:`Enum.__str__() <enum.Enum.__str__>`: for enums inheriting from
675
:class:`~enum.ReprEnum` it will be the member's value; for all other enums
676
it will be the enum and member name (e.g. ``Color.RED``).
677
678
* Added a new *boundary* class parameter to :class:`~enum.Flag` enums
679
and the :class:`~enum.FlagBoundary` enum with its options,
680
to control how to handle out-of-range flag values.
681
682
* Added the :func:`~enum.verify` enum decorator
683
and the :class:`~enum.EnumCheck` enum with its options,
684
to check enum classes against several specific constraints.
685
686
* Added the :func:`~enum.member` and :func:`~enum.nonmember` decorators,
687
to ensure the decorated object is/is not converted to an enum member.
688
689
* Added the :func:`~enum.property` decorator,
690
which works like :func:`property` except for enums.
691
Use this instead of :func:`types.DynamicClassAttribute`.
692
693
* Added the :func:`~enum.global_enum` enum decorator,
694
which adjusts :meth:`~object.__repr__` and :meth:`~object.__str__`
695
to show values as members of their module rather than the enum class.
696
For example, ``'re.ASCII'`` for the :const:`~re.ASCII` member
697
of :class:`re.RegexFlag` rather than ``'RegexFlag.ASCII'``.
698
699
* Enhanced :class:`~enum.Flag` to support
700
:func:`len`, iteration and :keyword:`in`/:keyword:`not in` on its members.
701
For example, the following now works:
702
``len(AFlag(3)) == 2 and list(AFlag(3)) == (AFlag.ONE, AFlag.TWO)``
703
704
* Changed :class:`~enum.Enum` and :class:`~enum.Flag`
705
so that members are now defined
706
before :meth:`~object.__init_subclass__` is called;
707
:func:`dir` now includes methods, etc., from mixed-in data types.
708
709
* Changed :class:`~enum.Flag`
710
to only consider primary values (power of two) canonical
711
while composite values (``3``, ``6``, ``10``, etc.) are considered aliases;
712
inverted flags are coerced to their positive equivalent.
713
714
715
.. _whatsnew311-fcntl:
716
717
fcntl
718
-----
719
720
* On FreeBSD, the :data:`!F_DUP2FD` and :data:`!F_DUP2FD_CLOEXEC` flags respectively
721
are supported, the former equals to ``dup2`` usage while the latter set
722
the ``FD_CLOEXEC`` flag in addition.
723
724
725
.. _whatsnew311-fractions:
726
727
fractions
728
---------
729
730
* Support :PEP:`515`-style initialization of :class:`~fractions.Fraction` from
731
string. (Contributed by Sergey B Kirpichev in :issue:`44258`.)
732
733
* :class:`~fractions.Fraction` now implements an ``__int__`` method, so
734
that an ``isinstance(some_fraction, typing.SupportsInt)`` check passes.
735
(Contributed by Mark Dickinson in :issue:`44547`.)
736
737
738
.. _whatsnew311-functools:
739
740
functools
741
---------
742
743
* :func:`functools.singledispatch` now supports :class:`types.UnionType`
744
and :class:`typing.Union` as annotations to the dispatch argument.::
745
746
>>> from functools import singledispatch
747
>>> @singledispatch
748
... def fun(arg, verbose=False):
749
... if verbose:
750
... print("Let me just say,", end=" ")
751
... print(arg)
752
...
753
>>> @fun.register
754
... def _(arg: int | float, verbose=False):
755
... if verbose:
756
... print("Strength in numbers, eh?", end=" ")
757
... print(arg)
758
...
759
>>> from typing import Union
760
>>> @fun.register
761
... def _(arg: Union[list, set], verbose=False):
762
... if verbose:
763
... print("Enumerate this:")
764
... for i, elem in enumerate(arg):
765
... print(i, elem)
766
...
767
768
(Contributed by Yurii Karabas in :issue:`46014`.)
769
770
771
.. _whatsnew311-gzip:
772
773
gzip
774
----
775
776
* The :func:`gzip.compress` function is now faster when used with the
777
**mtime=0** argument as it delegates the compression entirely to a single
778
:func:`zlib.compress` operation. There is one side effect of this change: The
779
gzip file header contains an "OS" byte in its header. That was traditionally
780
always set to a value of 255 representing "unknown" by the :mod:`gzip`
781
module. Now, when using :func:`~gzip.compress` with **mtime=0**, it may be
782
set to a different value by the underlying zlib C library Python was linked
783
against.
784
(See :gh:`112346` for details on the side effect.)
785
786
.. _whatsnew311-hashlib:
787
788
hashlib
789
-------
790
791
* :func:`hashlib.blake2b` and :func:`hashlib.blake2s` now prefer `libb2`_
792
over Python's vendored copy.
793
(Contributed by Christian Heimes in :issue:`47095`.)
794
795
* The internal ``_sha3`` module with SHA3 and SHAKE algorithms now uses
796
*tiny_sha3* instead of the *Keccak Code Package* to reduce code and binary
797
size. The :mod:`hashlib` module prefers optimized SHA3 and SHAKE
798
implementations from OpenSSL. The change affects only installations without
799
OpenSSL support.
800
(Contributed by Christian Heimes in :issue:`47098`.)
801
802
* Add :func:`hashlib.file_digest`, a helper function for efficient hashing
803
of files or file-like objects.
804
(Contributed by Christian Heimes in :gh:`89313`.)
805
806
807
.. _whatsnew311-idle:
808
809
IDLE and idlelib
810
----------------
811
812
* Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex
813
Waygood and Terry Jan Reedy in :issue:`45447`.)
814
815
* Include prompts when saving Shell with inputs and outputs.
816
(Contributed by Terry Jan Reedy in :gh:`95191`.)
817
818
819
.. _whatsnew311-inspect:
820
821
inspect
822
-------
823
824
* Add :func:`~inspect.getmembers_static` to return all members without
825
triggering dynamic lookup via the descriptor protocol. (Contributed by
826
Weipeng Hong in :issue:`30533`.)
827
828
* Add :func:`~inspect.ismethodwrapper`
829
for checking if the type of an object is a :class:`~types.MethodWrapperType`.
830
(Contributed by Hakan Çelik in :issue:`29418`.)
831
832
* Change the frame-related functions in the :mod:`inspect` module to return new
833
:class:`~inspect.FrameInfo` and :class:`~inspect.Traceback` class instances
834
(backwards compatible with the previous :term:`named tuple`-like interfaces)
835
that includes the extended :pep:`657` position information (end
836
line number, column and end column). The affected functions are:
837
838
* :func:`inspect.getframeinfo`
839
* :func:`inspect.getouterframes`
840
* :func:`inspect.getinnerframes`,
841
* :func:`inspect.stack`
842
* :func:`inspect.trace`
843
844
(Contributed by Pablo Galindo in :gh:`88116`.)
845
846
847
.. _whatsnew311-locale:
848
849
locale
850
------
851
852
* Add :func:`locale.getencoding` to get the current locale encoding. It is similar to
853
``locale.getpreferredencoding(False)`` but ignores the
854
:ref:`Python UTF-8 Mode <utf8-mode>`.
855
856
857
.. _whatsnew311-logging:
858
859
logging
860
-------
861
862
* Added :func:`~logging.getLevelNamesMapping`
863
to return a mapping from logging level names (e.g. ``'CRITICAL'``)
864
to the values of their corresponding :ref:`levels` (e.g. ``50``, by default).
865
(Contributed by Andrei Kulakovin in :gh:`88024`.)
866
867
* Added a :meth:`~logging.handlers.SysLogHandler.createSocket` method
868
to :class:`~logging.handlers.SysLogHandler`, to match
869
:meth:`SocketHandler.createSocket()
870
<logging.handlers.SocketHandler.createSocket>`.
871
It is called automatically during handler initialization
872
and when emitting an event, if there is no active socket.
873
(Contributed by Kirill Pinchuk in :gh:`88457`.)
874
875
876
.. _whatsnew311-math:
877
878
math
879
----
880
881
* Add :func:`math.exp2`: return 2 raised to the power of x.
882
(Contributed by Gideon Mitchell in :issue:`45917`.)
883
884
* Add :func:`math.cbrt`: return the cube root of x.
885
(Contributed by Ajith Ramachandran in :issue:`44357`.)
886
887
* The behaviour of two :func:`math.pow` corner cases was changed, for
888
consistency with the IEEE 754 specification. The operations
889
``math.pow(0.0, -math.inf)`` and ``math.pow(-0.0, -math.inf)`` now return
890
``inf``. Previously they raised :exc:`ValueError`. (Contributed by Mark
891
Dickinson in :issue:`44339`.)
892
893
* The :data:`math.nan` value is now always available.
894
(Contributed by Victor Stinner in :issue:`46917`.)
895
896
897
.. _whatsnew311-operator:
898
899
operator
900
--------
901
902
* A new function ``operator.call`` has been added, such that
903
``operator.call(obj, *args, **kwargs) == obj(*args, **kwargs)``.
904
(Contributed by Antony Lee in :issue:`44019`.)
905
906
907
.. _whatsnew311-os:
908
909
os
910
--
911
912
* On Windows, :func:`os.urandom` now uses ``BCryptGenRandom()``,
913
instead of ``CryptGenRandom()`` which is deprecated.
914
(Contributed by Donghee Na in :issue:`44611`.)
915
916
917
.. _whatsnew311-pathlib:
918
919
pathlib
920
-------
921
922
* :meth:`~pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` return only
923
directories if *pattern* ends with a pathname components separator:
924
:data:`~os.sep` or :data:`~os.altsep`.
925
(Contributed by Eisuke Kawasima in :issue:`22276` and :issue:`33392`.)
926
927
928
.. _whatsnew311-re:
929
930
re
931
--
932
933
* Atomic grouping (``(?>...)``) and possessive quantifiers (``*+``, ``++``,
934
``?+``, ``{m,n}+``) are now supported in regular expressions.
935
(Contributed by Jeffrey C. Jacobs and Serhiy Storchaka in :issue:`433030`.)
936
937
938
.. _whatsnew311-shutil:
939
940
shutil
941
------
942
943
* Add optional parameter *dir_fd* in :func:`shutil.rmtree`.
944
(Contributed by Serhiy Storchaka in :issue:`46245`.)
945
946
947
.. _whatsnew311-socket:
948
949
socket
950
------
951
952
* Add CAN Socket support for NetBSD.
953
(Contributed by Thomas Klausner in :issue:`30512`.)
954
955
* :meth:`~socket.create_connection` has an option to raise, in case of
956
failure to connect, an :exc:`ExceptionGroup` containing all errors
957
instead of only raising the last error.
958
(Contributed by Irit Katriel in :issue:`29980`.)
959
960
961
.. _whatsnew311-sqlite3:
962
963
sqlite3
964
-------
965
966
* You can now disable the authorizer by passing :const:`None` to
967
:meth:`~sqlite3.Connection.set_authorizer`.
968
(Contributed by Erlend E. Aasland in :issue:`44491`.)
969
970
* Collation name :meth:`~sqlite3.Connection.create_collation` can now
971
contain any Unicode character. Collation names with invalid characters
972
now raise :exc:`UnicodeEncodeError` instead of :exc:`sqlite3.ProgrammingError`.
973
(Contributed by Erlend E. Aasland in :issue:`44688`.)
974
975
* :mod:`sqlite3` exceptions now include the SQLite extended error code as
976
:attr:`~sqlite3.Error.sqlite_errorcode` and the SQLite error name as
977
:attr:`~sqlite3.Error.sqlite_errorname`.
978
(Contributed by Aviv Palivoda, Daniel Shahaf, and Erlend E. Aasland in
979
:issue:`16379` and :issue:`24139`.)
980
981
* Add :meth:`~sqlite3.Connection.setlimit` and
982
:meth:`~sqlite3.Connection.getlimit` to :class:`sqlite3.Connection` for
983
setting and getting SQLite limits by connection basis.
984
(Contributed by Erlend E. Aasland in :issue:`45243`.)
985
986
* :mod:`sqlite3` now sets :attr:`sqlite3.threadsafety` based on the default
987
threading mode the underlying SQLite library has been compiled with.
988
(Contributed by Erlend E. Aasland in :issue:`45613`.)
989
990
* :mod:`sqlite3` C callbacks now use unraisable exceptions if callback
991
tracebacks are enabled. Users can now register an
992
:func:`unraisable hook handler <sys.unraisablehook>` to improve their debug
993
experience.
994
(Contributed by Erlend E. Aasland in :issue:`45828`.)
995
996
* Fetch across rollback no longer raises :exc:`~sqlite3.InterfaceError`.
997
Instead we leave it to the SQLite library to handle these cases.
998
(Contributed by Erlend E. Aasland in :issue:`44092`.)
999
1000
* Add :meth:`~sqlite3.Connection.serialize` and