Skip to content

Commit

Permalink
pythonGH-96073: Fix wild replacement in inspect.formatannotation (pyt…
Browse files Browse the repository at this point in the history
…hon#96074)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
  • Loading branch information
2 people authored and mpage committed Oct 11, 2022
1 parent bd66031 commit 41b8172
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 @@ -1433,7 +1433,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 41b8172

Please sign in to comment.