diff --git a/Lib/inspect.py b/Lib/inspect.py index fcfe3b191ab503..a9ff526b50c546 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -153,7 +153,6 @@ import itertools import linecache import os -import re import sys import tokenize import token @@ -1334,10 +1333,10 @@ def formatannotation(annotation, base_module=None, *, quote_annotation_strings=T if not quote_annotation_strings and isinstance(annotation, str): return annotation if getattr(annotation, '__module__', None) == 'typing': - def repl(match): - text = match.group() - return text.removeprefix('typing.') - return re.sub(r'[\w\.]+', repl, repr(annotation)) + return (repr(annotation) + .replace(".typing.", "@TYPING@") + .replace("typing.", "") + .replace("@TYPING@", ".typing.")) if isinstance(annotation, types.GenericAlias): return str(annotation) if isinstance(annotation, type): diff --git a/Misc/NEWS.d/next/Library/2025-02-18-05-04-13.gh-issue-130167.aOgAz_.rst b/Misc/NEWS.d/next/Library/2025-02-18-05-04-13.gh-issue-130167.aOgAz_.rst new file mode 100644 index 00000000000000..60fa91246f8aca --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-02-18-05-04-13.gh-issue-130167.aOgAz_.rst @@ -0,0 +1 @@ +Improve speed of :func:`!inspect.formatannotation`. Patch by Semyon Moroz.