GH-96073: Fix wild replacement in inspect.formatannotation (#96074)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
Anh71me 2022-10-08 02:23:06 +08:00 committed by GitHub
parent 676d8ef380
commit d5fea01d9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 26 additions and 1 deletions

View File

@ -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):

View File

@ -1421,6 +1421,13 @@ class TestClassesAndFunctions(unittest.TestCase):
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):

View File

View File

@ -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]

View File

@ -0,0 +1 @@
In :mod:`inspect`, fix overeager replacement of "`typing.`" in formatting annotations.