Skip to content

Commit 107ba92

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 a421c87 commit 107ba92

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
@@ -1448,7 +1448,10 @@ def getargvalues(frame):
14481448

14491449
def formatannotation(annotation, base_module=None):
14501450
if getattr(annotation, '__module__', None) == 'typing':
1451-
return repr(annotation).replace('typing.', '')
1451+
def repl(match):
1452+
text = match.group()
1453+
return text.removeprefix('typing.')
1454+
return re.sub(r'[\w\.]+', repl, repr(annotation))
14521455
if isinstance(annotation, types.GenericAlias):
14531456
return str(annotation)
14541457
if isinstance(annotation, type):

Lib/test/test_inspect.py

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

14231423

1424+
class TestFormatAnnotation(unittest.TestCase):
1425+
def test_typing_replacement(self):
1426+
from test.typinganndata.ann_module9 import ann, ann1
1427+
self.assertEqual(inspect.formatannotation(ann), 'Union[List[str], int]')
1428+
self.assertEqual(inspect.formatannotation(ann1), 'Union[List[testModule.typing.A], int]')
1429+
1430+
14241431
class TestIsDataDescriptor(unittest.TestCase):
14251432

14261433
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)