* Records the same objects for each member of family before execution
* Records derived values when recording the trace
* This makes sure that specialization, or deoptimization, does not cause invalid values to be recorded
Gregory P. Smith [Tue, 28 Apr 2026 08:06:23 +0000 (01:06 -0700)]
GH-83065: Fix import deadlock by implementing hierarchical module locking (GH-137196)
Make _find_and_load() acquire the module locks for the full
dotted-name chain (parent before child) when loading a nested module, so
both threads contend on the same first lock and serialise instead of
deadlocking.
When acquiring a parent's lock would itself deadlock with another thread
that is loading that parent (cross-package circular imports), the parent's
lock is skipped and the partially-initialised parent is accepted -- the
same policy _lock_unlock_module() already applies on the existing code
path -- so concurrent circular imports that worked before continue to work.
Alex Grönholm [Tue, 28 Apr 2026 05:26:38 +0000 (08:26 +0300)]
gh-125862: Keep ContextDecorator open across generator/coroutine execution (GH-136212)
ContextDecorator and AsyncContextDecorator (and therefore @contextmanager
and @asynccontextmanager used as decorators) now detect generator,
coroutine, and asynchronous generator functions and emit a wrapper of the
matching kind, so the context manager spans iteration or await rather than
just the call that constructs the lazy object. Wrapped generators are
explicitly closed when iteration ends.
For asynchronous generator wrappers, values passed via asend() and
exceptions via athrow() are not forwarded to the wrapped generator.
AsyncContextDecorator now also accepts synchronous functions and
generators, returning an asynchronous wrapper; ContextDecorator remains
the recommended choice for those.
inspect.isgeneratorfunction(), iscoroutinefunction(), and
isasyncgenfunction() now return True for the decorated result when the
input is of that kind.
---------
Co-authored-by: Gregory P. Smith <greg@krypto.org>
Constant added to Linux 6.16. See the LWN article:
https://lwn.net/Articles/1023085/
Co-authored-by: Brian Schubert <brianm.schubert@gmail.com> Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> Co-authored-by: Victor Stinner <vstinner@python.org> Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Gregory P. Smith [Mon, 27 Apr 2026 01:42:13 +0000 (18:42 -0700)]
Document that multiprocessing treats local same-user processes as trusted (GH-149001)
Clarify in the Authentication keys section that the authkey handshake
covers Listener/Client (addressable endpoints) only, not the anonymous
pipes behind Pipe() and Queue, and that isolation between same-user
processes must be arranged at the OS level.
Gregory P. Smith [Mon, 27 Apr 2026 00:40:20 +0000 (17:40 -0700)]
gh-47798: Refactor the POSIX subprocess.Popen._communicate selector loop into helpers (GH-149032)
No public API change. Lift the per-iteration select/read/write loop out of
Popen._communicate (POSIX) into a module-level _communicate_io_posix(), with
small _flush_stdin / _make_input_view / _translate_newlines helpers alongside
it. Popen._communicate calls the helper and persists the returned input
offset for resume-after-timeout.
Retire the private Popen._remaining_time method in favor of module-level
_deadline_remaining; all call sites (POSIX and Windows) updated.
Defensive behavioural deltas: the stdin and stdout/stderr .close() calls in
the I/O loop now swallow BrokenPipeError / OSError, matching __exit__ and the
no-input path; previously these were bare.
Adds test_communicate_timeout_resume_partial_write to cover _input_offset
bookkeeping across TimeoutExpired/resume.
gh-146455: Fix O(N²) in add_const() after constant folding moved to CFG (#146456)
The add_const() function in flowgraph.c uses a linear search over the
consts list to find the index of a constant. After gh-126835 moved
constant folding from the AST optimizer to the CFG optimizer, this
function is now called N times for N inner tuple elements during
fold_tuple_of_constants(), resulting in O(N²) total time.
Fix by maintaining an auxiliary _Py_hashtable_t that maps object
pointers to their indices in the consts list, providing O(1) lookup.
For a file with 100,000 constant 2-tuples:
- Before: 10.38s (add_const occupies 83.76% of CPU time)
- After: 1.48s
Gregory P. Smith [Sun, 26 Apr 2026 04:01:33 +0000 (21:01 -0700)]
gh-141473: Speed up subprocess test_communicate_timeout_large_input long tail (#149003)
gh-141473: Speed up test_communicate_timeout_large_input
Replace the slow reader's 30s sleep with a parent-driven wake over a
loopback socket so post-timeout communicate() doesn't block waiting
for the child to wake on its own. Worst-case runtime: ~30s -> <1s.
Add `canonical=False` keyword argument to `a2b_base64`, `a2b_base32`, `a2b_base85`, and `a2b_ascii85` (and their `base64` module wrappers). When `canonical=True`, non-canonical encodings are rejected per [RFC 4648 section 3.5](https://datatracker.ietf.org/doc/html/rfc4648.html#section-3.5).
This is independent of `strict_mode`.
For base85/ascii85, the check also rejects single-character final groups (never produced by a conforming encoder) and verifies partial group padding matches what the encoder would produce.
Co-authored-by: Serhiy Storchaka via lots of great code review!
gh-142186: Revert the unintended value change in the `PY_MONITORING_EVENT_*` values from gh-146182 (gh-148955)
https://github.com/python/cpython/pull/146182 left an unintended change in the `PY_MONITORING_*` macro values. This change reverts that part to avoid a user visible impact.
Gregory P. Smith [Fri, 24 Apr 2026 16:36:46 +0000 (09:36 -0700)]
Improve `hash()` builtin docstring with caveats. (GH-125229)
Improve `hash()` builtin docstring with caveats.
Mention its return type and that the value can be expected to change between
processes (hash randomization).
Why? The `hash` builtin gets reached for and used by a lot of people whether it
is the right tool or not. IDEs surface docstrings and people use pydoc and
`help(hash)`.
Hai Zhu [Fri, 24 Apr 2026 09:37:01 +0000 (17:37 +0800)]
gh-146073: Add fitness/exit quality mechanism for JIT trace frontend (GH-148089)
* Replaces ad-hoc logic for ending traces with a simple inequality: `fitness < exit_quality`
* Fitness starts high and is reduced for branches, backward edges, calls and trace length
* Exit quality reflect how good a spot that instruction is to end a trace. Closing a loop is very, specializable instructions are very low and the others in between.
gh-145239: Accept unary plus literal pattern (#148566)
Add '+' alternatives to signed_number and signed_real_number grammar
rules, mirroring how unary minus is already handled for pattern matching.
Unary plus is a no-op on numbers so the value is returned directly without
wrapping in a UnaryOp node.
Sam Gross [Thu, 23 Apr 2026 18:42:57 +0000 (14:42 -0400)]
gh-113956: Make intern_common thread-safe in free-threaded build (gh-148886)
Avoid racing with the owning thread's refcount operations when
immortalizing an interned string: if we don't own it and its refcount
isn't merged, intern a copy we own instead. Use atomic stores in
_Py_SetImmortalUntracked so concurrent atomic reads are race-free.
Petr Viktorin [Thu, 23 Apr 2026 09:52:13 +0000 (11:52 +0200)]
gh-146636: Improve ABI/feature selection, add new header for it (GH-148302)
Improve ABI/feature selection, add new header for it.
Add a test that Python headers themselves don't use
Py_GIL_DISABLED in abi3t: abi3 and abi3t ought to be the
same except the _Py_OPAQUE_PYOBJECT differences.
This is done using the GCC-only poison pragma.
Co-authored-by: Victor Stinner <vstinner@python.org>
gh-119180: Document the `format` parameter in `typing.get_type_hints()` (#143758)
Do not mention `__annotations__` dictionaries, as this is slightly
outdated since 3.14.
Rewrite the note about possible exceptions for clarity. Also do not
mention imported type aliases, as since 3.12 aliases with the `type`
statement do not suffer from this limitation anymore.
John Seong [Thu, 23 Apr 2026 02:46:04 +0000 (10:46 +0800)]
gh-142965: Fix Concatenate documentation to reflect valid use cases (#143316)
The documentation previously stated that Concatenate is only valid
when used as the first argument to Callable, but according to PEP 612,
it can also be used when instantiating user-defined generic classes
with ParamSpec parameters.
Sam Gross [Wed, 22 Apr 2026 18:31:19 +0000 (14:31 -0400)]
gh-148820: Fix _PyRawMutex use-after-free on spurious semaphore wakeup (gh-148852)
_PyRawMutex_UnlockSlow CAS-removes the waiter from the list and then
calls _PySemaphore_Wakeup, with no handshake. If _PySemaphore_Wait
returns Py_PARK_INTR, the waiter can destroy its stack-allocated
semaphore before the unlocker's Wakeup runs, causing a fatal error from
ReleaseSemaphore / sem_post.
Loop in _PyRawMutex_LockSlow until _PySemaphore_Wait returns Py_PARK_OK,
which is only signalled when a matching Wakeup has been observed.
Also include GetLastError() and the handle in the Windows fatal messages
in _PySemaphore_Init, _PySemaphore_Wait, and _PySemaphore_Wakeup to make
similar races easier to diagnose in the future.
gh-142186: Allow all PEP-669 events to be per-code object and disableable (GH-146182)
* Make the `PY_UNWIND` monitoring event available as a code-local
event to allow trapping on function exit events when an exception
bubbles up. This complements the PY_RETURN event by allowing to
catch any function exit event.
* Allow `PY_UNWIND` to be `DISABLE`d; disabling it disables the event for the whole code object.
* Do the above for `PY_THROW`, `RAISE`, `EXCEPTION_HANDLED`, and `RERAISE` events.
Roman Donchenko [Mon, 20 Apr 2026 20:19:43 +0000 (23:19 +0300)]
gh-108411: Make typing.IO/BinaryIO arguments positional-only (#142906)
`IO` is purported to be the type of the file objects returned by `open`.
However, all methods on those objects take positional-only arguments, while
`IO`'s methods are declared with regular arguments. As such, the file objects
cannot actually be considered to implement `IO`. The same thing applies to
`BinaryIO`.
Fix this by adjusting the definition of these ABCs to match the file objects.
This is technically a breaking change, but it is unlikely to actually break
anything:
* These methods should never be called at runtime, since they are abstract.
Therefore, this should not cause any runtime errors.
* In typeshed these arguments are already positional-only, so this should
not cause any errors during typechecking either.
If _BlocksOutputBuffer_Finish() fails (memory allocation failure),
PyBytesWriter_Discard() is called on the writer. Then if
_BlocksOutputBuffer_OnError() is called, it calls again
PyBytesWriter_Discard() causing a double free.
Fix _BlocksOutputBuffer_Finish() by setting buffer->writer to NULL,
so _BlocksOutputBuffer_OnError() does nothing instead of calling
PyBytesWriter_Discard() again.
gh-148653: Fix some marshal errors related to recursive immutable objects (GH-148698)
Forbid marshalling recursive code, slice and frozendict objects which
cannot be correctly unmarshalled.
Reject invalid marshal data produced by marshalling recursive frozendict
objects which was previously incorrectly unmarshalled.
Add multiple tests for recursive data structures.
gh-148651: Fix refcount leak in _zstd decompressor options (#148657)
The option parsing in Modules/_zstd/decompressor.c had a missing Py_DECREF(value) before the early return -1 when PyLong_AsInt(key) fails. The identical code in Modules/_zstd/compressor.c line 158 has the fix.
Victor Stinner [Thu, 16 Apr 2026 17:13:25 +0000 (19:13 +0200)]
gh-148535: Don't use gcc -fprofile-update=atomic flag on i686 (#148554)
The -fprofile-update=atomic flag was added to fix a random GCC
internal error on PGO build (gh-145801) caused by corruption of
profile data (.gcda files). The problem is that it makes the PGO
build way slower (up to 47x slower) on i686. Since the GCC internal
error was not seen on i686 so far, don't use -fprofile-update=atomic
on i686.
Mark Shannon [Thu, 16 Apr 2026 14:33:09 +0000 (15:33 +0100)]
GH-146128: Fix AArch64 multi-instruction constants and relocations (GH-148598)
Fix AArch64 multi-instruction constants and relocations
* Elimates rendundant orr xN, xN, 0xffff after 16 or 32 bit loads
* Merges adrp (21rx) and ldr (12) relocations into single 33rx relocation, when safe to do so.
Mark Shannon [Thu, 16 Apr 2026 14:22:22 +0000 (15:22 +0100)]
GH-145668: Add FOR_ITER specialization for virtual iterators. Specialize GET_ITER. (GH-147967)
* Add FOR_ITER_VIRTUAL to specialize FOR_ITER for virtual iterators
* Add GET_ITER_SELF to specialize GET_ITER for iterators (including generators)
* Add GET_ITER_VIRTUAL to specialize GET_ITER for iterables as virtual iterators
* Add new (internal) _tp_iteritem function slot to PyTypeObject
* Put limited RESUME at start of genexpr for free-threading. Fix up exception handling in genexpr