gh-150816: Speed up inspect.signature() for Python functions - #157463
Open
eendebakpt wants to merge 3 commits into
Open
eendebakpt wants to merge 3 commits into
eendebakpt wants to merge 3 commits into
Conversation
For real Python functions the parameter kinds and defaults come straight from the code object, so the validation done by Parameter.__init__ is redundant. Construct the Parameter objects directly, falling back to the regular constructor for names that are not plain identifiers (e.g. the ".0" implicit argument of comprehensions). Parameter subclasses and duck-typed functions keep the full validation. inspect.signature() on a function with 7 parameters: 23.4 us -> 14.5 us. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Move the helper to Parameter._from_code(). Add tests that a Signature subclass overriding _parameter_cls still gets its own Parameter class (the concern raised on pythongh-150823), and that parameter names of function-like objects are still validated. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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.
For a Python function,
_signature_from_function()builds everyParameterthrough the public constructor, which validates the kind, the default and the name. This PR adds a privateParameter._from_code()that fills the slots directly and checks only the name.This picks up #150823 and addresses its review comments:
Signature._parameter_clsisParameteritself. (subclasses tested intest_signature_parameter_cls_subclass).test_signature_functionlike_invalid_names).Benchmark script
Windows x64 release build. Base and PR
Lib/inspect.pywere swapped viaPYTHONPATHon the same interpreter. Each figure is the best of 3 interleaved runs, each the minimum of 15 repeats.Generated with Claude Code