Skip to content

Commit a3a3701

Browse files
GH-96073: Fix wild replacement in inspect.formatannotation (GH-96074)
Co-authored-by: Jelle Zijlstra <[email protected]> (cherry picked from commit d5fea01) Co-authored-by: Anh71me <[email protected]>
1 parent e73cb54 commit a3a3701

File tree

5 files changed

+26
-1
lines changed

5 files changed

+26
-1
lines changed

Lib/inspect.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1356,7 +1356,10 @@ def getargvalues(frame):
13561356

13571357
def formatannotation(annotation, base_module=None):
13581358
if getattr(annotation, '__module__', None) == 'typing':
1359-
return repr(annotation).replace('typing.', '')
1359+
def repl(match):
1360+
text = match.group()
1361+
return text.removeprefix('typing.')
1362+
return re.sub(r'[\w\.]+', repl, repr(annotation))
13601363
if isinstance(annotation, types.GenericAlias):
13611364
return str(annotation)
13621365
if isinstance(annotation, type):

Lib/test/test_inspect.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1418,6 +1418,13 @@ def wrapper(a, b):
14181418
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True), {'x': int})
14191419

14201420

1421+
class TestFormatAnnotation(unittest.TestCase):
1422+
def test_typing_replacement(self):
1423+
from test.typinganndata.ann_module9 import ann, ann1
1424+
self.assertEqual(inspect.formatannotation(ann), 'Union[List[str], int]')
1425+
self.assertEqual(inspect.formatannotation(ann1), 'Union[List[testModule.typing.A], int]')
1426+
1427+
14211428
class TestIsDataDescriptor(unittest.TestCase):
14221429

14231430
def test_custom_descriptors(self):

Lib/test/typinganndata/__init__.py

Whitespace-only changes.

Lib/test/typinganndata/ann_module9.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Test ``inspect.formatannotation``
2+
# https://github.com/python/cpython/issues/96073
3+
4+
from typing import Union, List
5+
6+
ann = Union[List[str], int]
7+
8+
# mock typing._type_repr behaviour
9+
class A: ...
10+
11+
A.__module__ = 'testModule.typing'
12+
A.__qualname__ = 'A'
13+
14+
ann1 = Union[List[A], int]
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
In :mod:`inspect`, fix overeager replacement of "`typing.`" in formatting annotations.

0 commit comments

Comments
 (0)