Skip to content

Commit e05c569

Browse files
committed
Merge remote-tracking branch 'upstream/main' into getannos
2 parents 2afb851 + 9836503 commit e05c569

File tree

142 files changed

+2336
-1416
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

142 files changed

+2336
-1416
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ repos:
4747
exclude: Lib/test/tokenizedata/coding20731.py
4848
- id: trailing-whitespace
4949
types_or: [c, inc, python, rst]
50+
- id: trailing-whitespace
51+
files: '\.(gram)$'
5052

5153
- repo: https://github.com/python-jsonschema/check-jsonschema
5254
rev: 0.33.0

Doc/deprecations/pending-removal-in-3.15.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ Pending removal in Python 3.15
8585
has been deprecated since Python 3.13.
8686
Use the class-based syntax or the functional syntax instead.
8787

88+
* When using the functional syntax of :class:`~typing.TypedDict`\s, failing
89+
to pass a value to the *fields* parameter (``TD = TypedDict("TD")``) or
90+
passing ``None`` (``TD = TypedDict("TD", None)``) has been deprecated
91+
since Python 3.13.
92+
Use ``class TD(TypedDict): pass`` or ``TD = TypedDict("TD", {})``
93+
to create a TypedDict with zero field.
94+
8895
* The :func:`typing.no_type_check_decorator` decorator function
8996
has been deprecated since Python 3.13.
9097
After eight years in the :mod:`typing` module,

Doc/library/annotationlib.rst

Lines changed: 127 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -127,34 +127,34 @@ Classes
127127

128128
Values are the result of evaluating the annotation expressions.
129129

130-
.. attribute:: FORWARDREF
130+
.. attribute:: VALUE_WITH_FAKE_GLOBALS
131131
:value: 2
132132

133+
Special value used to signal that an annotate function is being
134+
evaluated in a special environment with fake globals. When passed this
135+
value, annotate functions should either return the same value as for
136+
the :attr:`Format.VALUE` format, or raise :exc:`NotImplementedError`
137+
to signal that they do not support execution in this environment.
138+
This format is only used internally and should not be passed to
139+
the functions in this module.
140+
141+
.. attribute:: FORWARDREF
142+
:value: 3
143+
133144
Values are real annotation values (as per :attr:`Format.VALUE` format)
134145
for defined values, and :class:`ForwardRef` proxies for undefined
135146
values. Real objects may contain references to :class:`ForwardRef`
136147
proxy objects.
137148

138149
.. attribute:: STRING
139-
:value: 3
150+
:value: 4
140151

141152
Values are the text string of the annotation as it appears in the
142153
source code, up to modifications including, but not restricted to,
143154
whitespace normalizations and constant values optimizations.
144155

145156
The exact values of these strings may change in future versions of Python.
146157

147-
.. attribute:: VALUE_WITH_FAKE_GLOBALS
148-
:value: 4
149-
150-
Special value used to signal that an annotate function is being
151-
evaluated in a special environment with fake globals. When passed this
152-
value, annotate functions should either return the same value as for
153-
the :attr:`Format.VALUE` format, or raise :exc:`NotImplementedError`
154-
to signal that they do not support execution in this environment.
155-
This format is only used internally and should not be passed to
156-
the functions in this module.
157-
158158
.. versionadded:: 3.14
159159

160160
.. class:: ForwardRef
@@ -485,3 +485,117 @@ annotations from the class and puts them in a separate attribute:
485485
typ.classvars = classvars # Store the ClassVars in a separate attribute
486486
return typ
487487
488+
489+
Limitations of the ``STRING`` format
490+
------------------------------------
491+
492+
The :attr:`~Format.STRING` format is meant to approximate the source code
493+
of the annotation, but the implementation strategy used means that it is not
494+
always possible to recover the exact source code.
495+
496+
First, the stringifier of course cannot recover any information that is not present in
497+
the compiled code, including comments, whitespace, parenthesization, and operations that
498+
get simplified by the compiler.
499+
500+
Second, the stringifier can intercept almost all operations that involve names looked
501+
up in some scope, but it cannot intercept operations that operate fully on constants.
502+
As a corollary, this also means it is not safe to request the ``STRING`` format on
503+
untrusted code: Python is powerful enough that it is possible to achieve arbitrary
504+
code execution even with no access to any globals or builtins. For example:
505+
506+
.. code-block:: pycon
507+
508+
>>> def f(x: (1).__class__.__base__.__subclasses__()[-1].__init__.__builtins__["print"]("Hello world")): pass
509+
...
510+
>>> annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
511+
Hello world
512+
{'x': 'None'}
513+
514+
.. note::
515+
This particular example works as of the time of writing, but it relies on
516+
implementation details and is not guaranteed to work in the future.
517+
518+
Among the different kinds of expressions that exist in Python,
519+
as represented by the :mod:`ast` module, some expressions are supported,
520+
meaning that the ``STRING`` format can generally recover the original source code;
521+
others are unsupported, meaning that they may result in incorrect output or an error.
522+
523+
The following are supported (sometimes with caveats):
524+
525+
* :class:`ast.BinOp`
526+
* :class:`ast.UnaryOp`
527+
528+
* :class:`ast.Invert` (``~``), :class:`ast.UAdd` (``+``), and :class:`ast.USub` (``-``) are supported
529+
* :class:`ast.Not` (``not``) is not supported
530+
531+
* :class:`ast.Dict` (except when using ``**`` unpacking)
532+
* :class:`ast.Set`
533+
* :class:`ast.Compare`
534+
535+
* :class:`ast.Eq` and :class:`ast.NotEq` are supported
536+
* :class:`ast.Lt`, :class:`ast.LtE`, :class:`ast.Gt`, and :class:`ast.GtE` are supported, but the operand may be flipped
537+
* :class:`ast.Is`, :class:`ast.IsNot`, :class:`ast.In`, and :class:`ast.NotIn` are not supported
538+
539+
* :class:`ast.Call` (except when using ``**`` unpacking)
540+
* :class:`ast.Constant` (though not the exact representation of the constant; for example, escape
541+
sequences in strings are lost; hexadecimal numbers are converted to decimal)
542+
* :class:`ast.Attribute` (assuming the value is not a constant)
543+
* :class:`ast.Subscript` (assuming the value is not a constant)
544+
* :class:`ast.Starred` (``*`` unpacking)
545+
* :class:`ast.Name`
546+
* :class:`ast.List`
547+
* :class:`ast.Tuple`
548+
* :class:`ast.Slice`
549+
550+
The following are unsupported, but throw an informative error when encountered by the
551+
stringifier:
552+
553+
* :class:`ast.FormattedValue` (f-strings; error is not detected if conversion specifiers like ``!r``
554+
are used)
555+
* :class:`ast.JoinedStr` (f-strings)
556+
557+
The following are unsupported and result in incorrect output:
558+
559+
* :class:`ast.BoolOp` (``and`` and ``or``)
560+
* :class:`ast.IfExp`
561+
* :class:`ast.Lambda`
562+
* :class:`ast.ListComp`
563+
* :class:`ast.SetComp`
564+
* :class:`ast.DictComp`
565+
* :class:`ast.GeneratorExp`
566+
567+
The following are disallowed in annotation scopes and therefore not relevant:
568+
569+
* :class:`ast.NamedExpr` (``:=``)
570+
* :class:`ast.Await`
571+
* :class:`ast.Yield`
572+
* :class:`ast.YieldFrom`
573+
574+
575+
Limitations of the ``FORWARDREF`` format
576+
----------------------------------------
577+
578+
The :attr:`~Format.FORWARDREF` format aims to produce real values as much
579+
as possible, with anything that cannot be resolved replaced with
580+
:class:`ForwardRef` objects. It is affected by broadly the same Limitations
581+
as the :attr:`~Format.STRING` format: annotations that perform operations on
582+
literals or that use unsupported expression types may raise exceptions when
583+
evaluated using the :attr:`~Format.FORWARDREF` format.
584+
585+
Below are a few examples of the behavior with unsupported expressions:
586+
587+
.. code-block:: pycon
588+
589+
>>> from annotationlib import get_annotations, Format
590+
>>> def zerodiv(x: 1 / 0): ...
591+
>>> get_annotations(zerodiv, format=Format.STRING)
592+
Traceback (most recent call last):
593+
...
594+
ZeroDivisionError: division by zero
595+
>>> get_annotations(zerodiv, format=Format.FORWARDREF)
596+
Traceback (most recent call last):
597+
...
598+
ZeroDivisionError: division by zero
599+
>>> def ifexp(x: 1 if y else 0): ...
600+
>>> get_annotations(ifexp, format=Format.STRING)
601+
{'x': '1'}

Doc/library/datetime.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,22 @@ A :class:`timedelta` object represents a duration, the difference between two
261261
>>> (d.days, d.seconds, d.microseconds)
262262
(-1, 86399, 999999)
263263

264+
Since the string representation of :class:`!timedelta` objects can be confusing,
265+
use the following recipe to produce a more readable format:
266+
267+
.. code-block:: pycon
268+
269+
>>> def pretty_timedelta(td):
270+
... if td.days >= 0:
271+
... return str(td)
272+
... return f'-({-td!s})'
273+
...
274+
>>> d = timedelta(hours=-1)
275+
>>> str(d) # not human-friendly
276+
'-1 day, 23:00:00'
277+
>>> pretty_timedelta(d)
278+
'-(1:00:00)'
279+
264280
265281
Class attributes:
266282

Doc/library/fcntl.rst

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,15 +107,15 @@ The module defines the following functions:
107107
passed to the C :c:func:`fcntl` call. The return value after a successful
108108
call is the contents of the buffer, converted to a :class:`bytes` object.
109109
The length of the returned object will be the same as the length of the
110-
*arg* argument. This is limited to 1024 bytes.
110+
*arg* argument.
111111

112112
If the :c:func:`fcntl` call fails, an :exc:`OSError` is raised.
113113

114114
.. note::
115-
If the type or the size of *arg* does not match the type or size
116-
of the argument of the operation (for example, if an integer is
115+
If the type or size of *arg* does not match the type or size
116+
of the operation's argument (for example, if an integer is
117117
passed when a pointer is expected, or the information returned in
118-
the buffer by the operating system is larger than 1024 bytes),
118+
the buffer by the operating system is larger than the size of *arg*),
119119
this is most likely to result in a segmentation violation or
120120
a more subtle data corruption.
121121

@@ -125,6 +125,9 @@ The module defines the following functions:
125125
Add support of arbitrary :term:`bytes-like objects <bytes-like object>`,
126126
not only :class:`bytes`.
127127

128+
.. versionchanged:: next
129+
The size of bytes-like objects is no longer limited to 1024 bytes.
130+
128131

129132
.. function:: ioctl(fd, request, arg=0, mutate_flag=True, /)
130133

@@ -161,8 +164,7 @@ The module defines the following functions:
161164
If the type or size of *arg* does not match the type or size
162165
of the operation's argument (for example, if an integer is
163166
passed when a pointer is expected, or the information returned in
164-
the buffer by the operating system is larger than 1024 bytes,
165-
or the size of the mutable bytes-like object is too small),
167+
the buffer by the operating system is larger than the size of *arg*),
166168
this is most likely to result in a segmentation violation or
167169
a more subtle data corruption.
168170

@@ -185,6 +187,10 @@ The module defines the following functions:
185187
The GIL is always released during a system call.
186188
System calls failing with EINTR are automatically retried.
187189

190+
.. versionchanged:: next
191+
The size of not mutated bytes-like objects is no longer
192+
limited to 1024 bytes.
193+
188194
.. function:: flock(fd, operation, /)
189195

190196
Perform the lock operation *operation* on file descriptor *fd* (file objects providing

Doc/library/heapq.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,7 @@ The strange invariant above is meant to be an efficient memory representation
315315
for a tournament. The numbers below are *k*, not ``a[k]``:
316316

317317
.. figure:: heapq-binary-tree.svg
318+
:class: invert-in-dark-mode
318319
:align: center
319320
:alt: Example (min-heap) binary tree.
320321

Doc/library/logging.rst

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1342,8 +1342,9 @@ functions.
13421342

13431343
.. function:: basicConfig(**kwargs)
13441344

1345-
Does basic configuration for the logging system by creating a
1346-
:class:`StreamHandler` with a default :class:`Formatter` and adding it to the
1345+
Does basic configuration for the logging system by either creating a
1346+
:class:`StreamHandler` with a default :class:`Formatter`
1347+
or using the given *formatter* instance, and adding it to the
13471348
root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
13481349
:func:`error` and :func:`critical` will call :func:`basicConfig` automatically
13491350
if no handlers are defined for the root logger.
@@ -1428,6 +1429,19 @@ functions.
14281429
| | which means that it will be treated the |
14291430
| | same as passing 'errors'. |
14301431
+--------------+---------------------------------------------+
1432+
| *formatter* | If specified, set this formatter instance |
1433+
| | (see :ref:`formatter-objects`) |
1434+
| | for all involved handlers. |
1435+
| | If not specified, the default is to create |
1436+
| | and use an instance of |
1437+
| | :class:`logging.Formatter` based on |
1438+
| | arguments *format*, *datefmt* and *style*. |
1439+
| | When *formatter* is specified together with |
1440+
| | any of the three arguments *format*, |
1441+
| | *datefmt* and *style*, a ``ValueError`` is |
1442+
| | raised to signal that these arguments would |
1443+
| | lose meaning otherwise. |
1444+
+--------------+---------------------------------------------+
14311445

14321446
.. versionchanged:: 3.2
14331447
The *style* argument was added.
@@ -1444,6 +1458,9 @@ functions.
14441458
.. versionchanged:: 3.9
14451459
The *encoding* and *errors* arguments were added.
14461460

1461+
.. versionchanged:: 3.15
1462+
The *formatter* argument was added.
1463+
14471464
.. function:: shutdown()
14481465

14491466
Informs the logging system to perform an orderly shutdown by flushing and

Doc/library/math.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,7 @@ Number-theoretic functions
144144

145145
.. function:: factorial(n)
146146

147-
Return *n* factorial as an integer. Raises :exc:`ValueError` if *n* is not integral or
148-
is negative.
147+
Return factorial of the nonnegative integer *n*.
149148

150149
.. versionchanged:: 3.10
151150
Floats with integral values (like ``5.0``) are no longer accepted.

Doc/library/shutil.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,10 @@ Directory and files operations
454454
:envvar:`PATH` environment variable is read from :data:`os.environ`,
455455
falling back to :data:`os.defpath` if it is not set.
456456

457+
If *cmd* contains a directory component, :func:`!which` only checks the
458+
specified path directly and does not search the directories listed in
459+
*path* or in the system's :envvar:`PATH` environment variable.
460+
457461
On Windows, the current directory is prepended to the *path* if *mode* does
458462
not include ``os.X_OK``. When the *mode* does include ``os.X_OK``, the
459463
Windows API ``NeedCurrentDirectoryForExePathW`` will be consulted to

Doc/library/stdtypes.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2269,6 +2269,18 @@ expression support in the :mod:`re` module).
22692269
>>> ' 1 2 3 '.split()
22702270
['1', '2', '3']
22712271

2272+
If *sep* is not specified or is ``None`` and *maxsplit* is ``0``, only
2273+
leading runs of consecutive whitespace are considered.
2274+
2275+
For example::
2276+
2277+
>>> "".split(None, 0)
2278+
[]
2279+
>>> " ".split(None, 0)
2280+
[]
2281+
>>> " foo ".split(maxsplit=0)
2282+
['foo ']
2283+
22722284

22732285
.. index::
22742286
single: universal newlines; str.splitlines method

0 commit comments

Comments
 (0)