gh-130167: Improve speed of inspect.formatannotation by replacing re#130242
gh-130167: Improve speed of inspect.formatannotation by replacing re#130242donbarbos wants to merge 8 commits intopython:mainfrom
inspect.formatannotation by replacing re#130242Conversation
inspect.formatannotation by replacing reinspect.formatannotation by replacing re
Misc/NEWS.d/next/Library/2025-02-18-05-04-13.gh-issue-130167.aOgAz_.rst
Outdated
Show resolved
Hide resolved
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
AA-Turner
left a comment
There was a problem hiding this comment.
I'm less sure this is worth it, the replacement isn't clearly better maintenence-wise.
What do the benchmarks look like if you extract repl to a module-level _formatannotation_repl and use .sub() on a pre-compiled pattern?
A
|
sorry, I forgot how python was compiled then :( but I'm pretty sure I compiled it with gcc last time so I reran the test with the following config args Old version (re.sub): 0.982520s
New version (.replace()): 0.701049s
Difference: 1.40x # sometimes it's 1.35xand if we rewrite old version of benchmark as you suggested: _pattern = re.compile(r"[\w\.]+")
def _repl(match):
text = match.group()
return text.removeprefix("typing.")
def old_format_annotation(annotation):
if getattr(annotation, "__module__", None) == "typing":
return re.sub(_pattern, _repl, repr(annotation))
return repr(annotation)we will get a bigger difference: Old version (re.sub): 1.027774s
New version (.replace()): 0.698902s
Difference: 1.47x # the result can drop to 1.40P.S.: another reason i like the PR version is because we get rid of the |
|
Out of curiosity, why use the little replace dance in the refactored code instead of just |
- Union[typing.List[str], typing.Dict[str, typing.Any]]
+ Union[List[str], Dict[str, Any]]The For what it’s worth: pat = re.compile(r"\b(?<!\.)typing\.")
pat.sub("", repr(annotation)) |
timeitbenchmark with my script:inspect_bench.py:Result: 2.0s -> 1.18s = x1.74 as fast
reuses #130167