Skip to content

Commit d5fea01

Browse files
iyumeJelleZijlstra
andauthored
GH-96073: Fix wild replacement in inspect.formatannotation (#96074)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 676d8ef commit d5fea01

File tree

5 files changed

+26
-1
lines changed

5 files changed

+26
-1
lines changed

Lib/inspect.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1433,7 +1433,10 @@ def getargvalues(frame):
14331433

14341434
def formatannotation(annotation, base_module=None):
14351435
if getattr(annotation, '__module__', None) == 'typing':
1436-
return repr(annotation).replace('typing.', '')
1436+
def repl(match):
1437+
text = match.group()
1438+
return text.removeprefix('typing.')
1439+
return re.sub(r'[\w\.]+', repl, repr(annotation))
14371440
if isinstance(annotation, types.GenericAlias):
14381441
return str(annotation)
14391442
if isinstance(annotation, type):

Lib/test/test_inspect.py

+7
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

+14
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]
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)