[mypyc] Create function wrappers of nested coroutines lazily - #22048
Merged
Merged
Conversation
Each instance of a nested async def's callable class used to get its own CPyFunction wrapper at instantiation. Creating it allocates a method def, a code object, a name string and the function object, which made defining a nested async def several times slower than calling it. The wrapper is only used for introspection (__name__, __code__, __defaults__, etc.), so create it on first access in the property getters and setters instead. Microbenchmark (separate=True, Python 3.14, arm64 macOS; ns per call of an outer coroutine that defines and awaits a nested async def): before 259.6 after 69.6 In production profiles of a large async service, CPyFunction_New and the wrapper's dealloc were ~0.16% of CPU.
Creating the wrapper may run arbitrary code (e.g. via GC) that could have initialized the attribute already, so only store it if still NULL.
p-sawicki
approved these changes
Sep 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Each nested async def instance used to get it's own freshly allocated
function wrapper object, which is only needed relatively rarely for
introspection (e.g.
__name__). This was slow to construct. Now weconstruct this lazily. On free-threaded builds we need to deal with
other threads racing as well.
Top-level coroutines and methods are unaffected. Their wrappers were
already created once at import time.
Microbenchmark results (Python 3.14, 1M iterations):