Skip to content

Commit

Permalink
GH-96073: Fix wild replacement in inspect.formatannotation (GH-96074)
Browse files Browse the repository at this point in the history
Co-authored-by: Jelle Zijlstra <[email protected]>
(cherry picked from commit d5fea01)

Co-authored-by: Anh71me <[email protected]>
  • Loading branch information
miss-islington and iyume authored Oct 7, 2022
1 parent a421c87 commit 107ba92
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1448,7 +1448,10 @@ def getargvalues(frame):

def formatannotation(annotation, base_module=None):
if getattr(annotation, '__module__', None) == 'typing':
return repr(annotation).replace('typing.', '')
def repl(match):
text = match.group()
return text.removeprefix('typing.')
return re.sub(r'[\w\.]+', repl, repr(annotation))
if isinstance(annotation, types.GenericAlias):
return str(annotation)
if isinstance(annotation, type):
Expand Down
7 changes: 7 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1421,6 +1421,13 @@ def wrapper(a, b):
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True), {'x': int})


class TestFormatAnnotation(unittest.TestCase):
def test_typing_replacement(self):
from test.typinganndata.ann_module9 import ann, ann1
self.assertEqual(inspect.formatannotation(ann), 'Union[List[str], int]')
self.assertEqual(inspect.formatannotation(ann1), 'Union[List[testModule.typing.A], int]')


class TestIsDataDescriptor(unittest.TestCase):

def test_custom_descriptors(self):
Expand Down
Empty file.
14 changes: 14 additions & 0 deletions Lib/test/typinganndata/ann_module9.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Test ``inspect.formatannotation``
# https://github.com/python/cpython/issues/96073

from typing import Union, List

ann = Union[List[str], int]

# mock typing._type_repr behaviour
class A: ...

A.__module__ = 'testModule.typing'
A.__qualname__ = 'A'

ann1 = Union[List[A], int]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
In :mod:`inspect`, fix overeager replacement of "`typing.`" in formatting annotations.

0 comments on commit 107ba92

Please sign in to comment.