mirror of https://github.com/python/cpython
GH-96073: Fix wild replacement in inspect.formatannotation (#96074)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
parent
676d8ef380
commit
d5fea01d9d
|
@ -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):
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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]
|
|
@ -0,0 +1 @@
|
|||
In :mod:`inspect`, fix overeager replacement of "`typing.`" in formatting annotations.
|
Loading…
Reference in New Issue