Skip to content

Commit 0a76abd

Browse files
Merge branch 'main' of https://github.com/python/cpython into cached-strs
2 parents f530250 + 631160c commit 0a76abd

File tree

89 files changed

+1341
-1998
lines changed

Some content is hidden

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

89 files changed

+1341
-1998
lines changed

Doc/c-api/datetime.rst

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,15 @@ Macros to create objects:
132132
resulting number of microseconds and seconds lie in the ranges documented for
133133
:class:`datetime.timedelta` objects.
134134
135+
135136
.. c:function:: PyObject* PyTimeZone_FromOffset(PyDateTime_DeltaType* offset)
136137
137138
Return a :class:`datetime.timezone` object with an unnamed fixed offset
138139
represented by the *offset* argument.
139140
140141
.. versionadded:: 3.7
141142
143+
142144
.. c:function:: PyObject* PyTimeZone_FromOffsetAndName(PyDateTime_DeltaType* offset, PyUnicode* name)
143145
144146
Return a :class:`datetime.timezone` object with a fixed offset represented
@@ -190,12 +192,21 @@ must not be ``NULL``, and the type is not checked:
190192
191193
Return the microsecond, as an int from 0 through 999999.
192194
195+
196+
.. c:function:: int PyDateTime_DATE_GET_FOLD(PyDateTime_DateTime *o)
197+
198+
Return the fold, as an int from 0 through 1.
199+
200+
.. versionadded:: 3.6
201+
202+
193203
.. c:function:: PyObject* PyDateTime_DATE_GET_TZINFO(PyDateTime_DateTime *o)
194204
195205
Return the tzinfo (which may be ``None``).
196206
197207
.. versionadded:: 3.10
198208
209+
199210
Macros to extract fields from time objects. The argument must be an instance of
200211
:c:data:`PyDateTime_Time`, including subclasses. The argument must not be ``NULL``,
201212
and the type is not checked:
@@ -219,6 +230,14 @@ and the type is not checked:
219230
220231
Return the microsecond, as an int from 0 through 999999.
221232
233+
234+
.. c:function:: int PyDateTime_TIME_GET_FOLD(PyDateTime_Time *o)
235+
236+
Return the fold, as an int from 0 through 1.
237+
238+
.. versionadded:: 3.6
239+
240+
222241
.. c:function:: PyObject* PyDateTime_TIME_GET_TZINFO(PyDateTime_Time *o)
223242
224243
Return the tzinfo (which may be ``None``).

Doc/howto/logging-cookbook.rst

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ messages should not. Here's how you can achieve this::
219219
logging.basicConfig(level=logging.DEBUG,
220220
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
221221
datefmt='%m-%d %H:%M',
222-
filename='/temp/myapp.log',
222+
filename='/tmp/myapp.log',
223223
filemode='w')
224224
# define a Handler which writes INFO messages or higher to the sys.stderr
225225
console = logging.StreamHandler()
@@ -270,6 +270,11 @@ are sent to both destinations.
270270
This example uses console and file handlers, but you can use any number and
271271
combination of handlers you choose.
272272

273+
Note that the above choice of log filename ``/tmp/myapp.log`` implies use of a
274+
standard location for temporary files on POSIX systems. On Windows, you may need to
275+
choose a different directory name for the log - just ensure that the directory exists
276+
and that you have the permissions to create and update files in it.
277+
273278

274279
Configuration server example
275280
----------------------------

Doc/library/ast.rst

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,10 +1028,11 @@ Control flow
10281028
.. class:: For(target, iter, body, orelse, type_comment)
10291029

10301030
A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a
1031-
single :class:`Name`, :class:`Tuple` or :class:`List` node. ``iter`` holds
1032-
the item to be looped over, again as a single node. ``body`` and ``orelse``
1033-
contain lists of nodes to execute. Those in ``orelse`` are executed if the
1034-
loop finishes normally, rather than via a ``break`` statement.
1031+
single :class:`Name`, :class:`Tuple`, :class:`List`, :class:`Attribute` or
1032+
:class:`Subscript` node. ``iter`` holds the item to be looped over, again
1033+
as a single node. ``body`` and ``orelse`` contain lists of nodes to execute.
1034+
Those in ``orelse`` are executed if the loop finishes normally, rather than
1035+
via a ``break`` statement.
10351036

10361037
.. attribute:: type_comment
10371038

Doc/library/asyncio-task.rst

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,24 @@ Creating Tasks
282282
Added the *context* parameter.
283283

284284

285+
Task Cancellation
286+
=================
287+
288+
Tasks can easily and safely be cancelled.
289+
When a task is cancelled, :exc:`asyncio.CancelledError` will be raised
290+
in the task at the next opportunity.
291+
292+
It is recommended that coroutines use ``try/finally`` blocks to robustly
293+
perform clean-up logic. In case :exc:`asyncio.CancelledError`
294+
is explicitly caught, it should generally be propagated when
295+
clean-up is complete. Most code can safely ignore :exc:`asyncio.CancelledError`.
296+
297+
Important asyncio components, like :class:`asyncio.TaskGroup` and the
298+
:func:`asyncio.timeout` context manager, are implemented using cancellation
299+
internally and might misbehave if a coroutine swallows
300+
:exc:`asyncio.CancelledError`.
301+
302+
285303
Task Groups
286304
===========
287305

@@ -537,6 +555,122 @@ Shielding From Cancellation
537555
Timeouts
538556
========
539557

558+
.. coroutinefunction:: timeout(delay)
559+
560+
An :ref:`asynchronous context manager <async-context-managers>`
561+
that can be used to limit the amount of time spent waiting on
562+
something.
563+
564+
*delay* can either be ``None``, or a float/int number of
565+
seconds to wait. If *delay* is ``None``, no time limit will
566+
be applied; this can be useful if the delay is unknown when
567+
the context manager is created.
568+
569+
In either case, the context manager can be rescheduled after
570+
creation using :meth:`Timeout.reschedule`.
571+
572+
Example::
573+
574+
async def main():
575+
async with asyncio.timeout(10):
576+
await long_running_task()
577+
578+
If ``long_running_task`` takes more than 10 seconds to complete,
579+
the context manager will cancel the current task and handle
580+
the resulting :exc:`asyncio.CancelledError` internally, transforming it
581+
into an :exc:`asyncio.TimeoutError` which can be caught and handled.
582+
583+
.. note::
584+
585+
The :func:`asyncio.timeout` context manager is what transforms
586+
the :exc:`asyncio.CancelledError` into an :exc:`asyncio.TimeoutError`,
587+
which means the :exc:`asyncio.TimeoutError` can only be caught
588+
*outside* of the context manager.
589+
590+
Example of catching :exc:`asyncio.TimeoutError`::
591+
592+
async def main():
593+
try:
594+
async with asyncio.timeout(10):
595+
await long_running_task()
596+
except TimeoutError:
597+
print("The long operation timed out, but we've handled it.")
598+
599+
print("This statement will run regardless.")
600+
601+
The context manager produced by :func:`asyncio.timeout` can be
602+
rescheduled to a different deadline and inspected.
603+
604+
.. class:: Timeout()
605+
606+
An :ref:`asynchronous context manager <async-context-managers>`
607+
that limits time spent inside of it.
608+
609+
.. versionadded:: 3.11
610+
611+
.. method:: when() -> float | None
612+
613+
Return the current deadline, or ``None`` if the current
614+
deadline is not set.
615+
616+
The deadline is a float, consistent with the time returned by
617+
:meth:`loop.time`.
618+
619+
.. method:: reschedule(when: float | None)
620+
621+
Change the time the timeout will trigger.
622+
623+
If *when* is `None`, any current deadline will be removed, and the
624+
context manager will wait indefinitely.
625+
626+
If *when* is a float, it is set as the new deadline.
627+
628+
.. method:: expired() -> bool
629+
630+
Return whether the context manager has exceeded its deadline
631+
(expired).
632+
633+
Example::
634+
635+
async def main():
636+
try:
637+
# We do not know the timeout when starting, so we pass ``None``.
638+
async with asyncio.timeout(None) as cm:
639+
# We know the timeout now, so we reschedule it.
640+
new_deadline = get_running_loop().time() + 10
641+
cm.reschedule(new_deadline)
642+
643+
await long_running_task()
644+
except TimeoutError:
645+
pass
646+
647+
if cm.expired:
648+
print("Looks like we haven't finished on time.")
649+
650+
Timeout context managers can be safely nested.
651+
652+
.. versionadded:: 3.11
653+
654+
.. coroutinefunction:: timeout_at(when)
655+
656+
Similar to :func:`asyncio.timeout`, except *when* is the absolute time
657+
to stop waiting, or ``None``.
658+
659+
Example::
660+
661+
async def main():
662+
loop = get_running_loop()
663+
deadline = loop.time() + 20
664+
try:
665+
async with asyncio.timeout_at(deadline):
666+
await long_running_task()
667+
except TimeoutError:
668+
print("The long operation timed out, but we've handled it.")
669+
670+
print("This statement will run regardless.")
671+
672+
.. versionadded:: 3.11
673+
540674
.. coroutinefunction:: wait_for(aw, timeout)
541675

542676
Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`

Doc/library/logging.handlers.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1018,6 +1018,8 @@ possible, while any potentially slow operations (such as sending an email via
10181018
have the task tracking API, which means that you can use
10191019
:class:`~queue.SimpleQueue` instances for *queue*.
10201020

1021+
.. note:: If you are using :mod:`multiprocessing`, you should avoid using
1022+
:class:`~queue.SimpleQueue` and instead use :class:`multiprocessing.Queue`.
10211023

10221024
.. method:: emit(record)
10231025

@@ -1091,6 +1093,9 @@ possible, while any potentially slow operations (such as sending an email via
10911093
task tracking API (though it's used if available), which means that you can
10921094
use :class:`~queue.SimpleQueue` instances for *queue*.
10931095

1096+
.. note:: If you are using :mod:`multiprocessing`, you should avoid using
1097+
:class:`~queue.SimpleQueue` and instead use :class:`multiprocessing.Queue`.
1098+
10941099
If ``respect_handler_level`` is ``True``, a handler's level is respected
10951100
(compared with the level for the message) when deciding whether to pass
10961101
messages to that handler; otherwise, the behaviour is as in previous Python

Doc/library/pathlib.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1300,7 +1300,8 @@ Below is a table mapping various :mod:`os` functions to their corresponding
13001300
:func:`os.path.basename` :data:`PurePath.name`
13011301
:func:`os.path.dirname` :data:`PurePath.parent`
13021302
:func:`os.path.samefile` :meth:`Path.samefile`
1303-
:func:`os.path.splitext` :data:`PurePath.suffix`
1303+
:func:`os.path.splitext` :data:`PurePath.stem` and
1304+
:data:`PurePath.suffix`
13041305
==================================== ==============================
13051306

13061307
.. rubric:: Footnotes

Doc/library/random.rst

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,28 @@ Functions for sequences
258258
The *population* must be a sequence. Automatic conversion of sets
259259
to lists is no longer supported.
260260

261+
Discrete distributions
262+
----------------------
263+
264+
The following function generates a discrete distribution.
265+
266+
.. function:: binomialvariate(n=1, p=0.5)
267+
268+
`Binomial distribution
269+
<http://mathworld.wolfram.com/BinomialDistribution.html>`_.
270+
Return the number of successes for *n* independent trials with the
271+
probability of success in each trial being *p*:
272+
273+
Mathematically equivalent to::
274+
275+
sum(random() < p for i in range(n))
276+
277+
The number of trials *n* should be a non-negative integer.
278+
The probability of success *p* should be between ``0.0 <= p <= 1.0``.
279+
The result is an integer in the range ``0 <= X <= n``.
280+
281+
.. versionadded:: 3.12
282+
261283

262284
.. _real-valued-distributions:
263285

@@ -452,16 +474,13 @@ Simulations::
452474
>>> # Deal 20 cards without replacement from a deck
453475
>>> # of 52 playing cards, and determine the proportion of cards
454476
>>> # with a ten-value: ten, jack, queen, or king.
455-
>>> dealt = sample(['tens', 'low cards'], counts=[16, 36], k=20)
456-
>>> dealt.count('tens') / 20
477+
>>> deal = sample(['tens', 'low cards'], counts=[16, 36], k=20)
478+
>>> deal.count('tens') / 20
457479
0.15
458480

459481
>>> # Estimate the probability of getting 5 or more heads from 7 spins
460482
>>> # of a biased coin that settles on heads 60% of the time.
461-
>>> def trial():
462-
... return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
463-
...
464-
>>> sum(trial() for i in range(10_000)) / 10_000
483+
>>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000
465484
0.4169
466485

467486
>>> # Probability of the median of 5 samples being in middle two quartiles

Doc/library/sqlite3.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1366,7 +1366,7 @@ of :func:`connect`. There are three options:
13661366
* Explicit: set *detect_types* to :const:`PARSE_COLNAMES`
13671367
* Both: set *detect_types* to
13681368
``sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES``.
1369-
Colum names take precedence over declared types.
1369+
Column names take precedence over declared types.
13701370

13711371
The following example illustrates the implicit and explicit approaches:
13721372

Doc/library/sys.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,7 @@ always available.
774774
that is deeper than the call stack, :exc:`ValueError` is raised. The default
775775
for *depth* is zero, returning the frame at the top of the call stack.
776776

777-
.. audit-event:: sys._getframe "" sys._getframe
777+
.. audit-event:: sys._getframe frame sys._getframe
778778

779779
.. impl-detail::
780780

@@ -1158,7 +1158,7 @@ always available.
11581158
line option or the :envvar:`PYTHONSAFEPATH` environment variable?
11591159

11601160
A program is free to modify this list for its own purposes. Only strings
1161-
and bytes should be added to :data:`sys.path`; all other data types are
1161+
should be added to :data:`sys.path`; all other data types are
11621162
ignored during import.
11631163

11641164

Doc/library/typing.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -683,7 +683,7 @@ These can be used as types in annotations and do not support ``[]``.
683683
from typing import Self
684684

685685
class Foo:
686-
def returns_self(self) -> Self:
686+
def return_self(self) -> Self:
687687
...
688688
return self
689689

@@ -696,7 +696,7 @@ These can be used as types in annotations and do not support ``[]``.
696696
Self = TypeVar("Self", bound="Foo")
697697

698698
class Foo:
699-
def returns_self(self: Self) -> Self:
699+
def return_self(self: Self) -> Self:
700700
...
701701
return self
702702

@@ -707,7 +707,7 @@ These can be used as types in annotations and do not support ``[]``.
707707
...
708708
return self
709709

710-
You should use use :data:`Self` as calls to ``SubclassOfFoo.returns_self`` would have
710+
You should use :data:`Self` as calls to ``SubclassOfFoo.return_self`` would have
711711
``Foo`` as the return type and not ``SubclassOfFoo``.
712712

713713
Other common use cases include:

Doc/reference/import.rst

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -800,10 +800,8 @@ environment variable and various other installation- and
800800
implementation-specific defaults. Entries in :data:`sys.path` can name
801801
directories on the file system, zip files, and potentially other "locations"
802802
(see the :mod:`site` module) that should be searched for modules, such as
803-
URLs, or database queries. Only strings and bytes should be present on
804-
:data:`sys.path`; all other data types are ignored. The encoding of bytes
805-
entries is determined by the individual :term:`path entry finders <path entry
806-
finder>`.
803+
URLs, or database queries. Only strings should be present on
804+
:data:`sys.path`; all other data types are ignored.
807805

808806
The :term:`path based finder` is a :term:`meta path finder`, so the import
809807
machinery begins the :term:`import path` search by calling the path

0 commit comments

Comments
 (0)