mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
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
5 changed files with 26 additions and 1 deletions
|
@ -1433,7 +1433,10 @@ def getargvalues(frame):
|
||||||
|
|
||||||
def formatannotation(annotation, base_module=None):
|
def formatannotation(annotation, base_module=None):
|
||||||
if getattr(annotation, '__module__', None) == 'typing':
|
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):
|
if isinstance(annotation, types.GenericAlias):
|
||||||
return str(annotation)
|
return str(annotation)
|
||||||
if isinstance(annotation, type):
|
if isinstance(annotation, type):
|
||||||
|
|
|
@ -1421,6 +1421,13 @@ class TestClassesAndFunctions(unittest.TestCase):
|
||||||
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True), {'x': int})
|
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):
|
class TestIsDataDescriptor(unittest.TestCase):
|
||||||
|
|
||||||
def test_custom_descriptors(self):
|
def test_custom_descriptors(self):
|
||||||
|
|
0
Lib/test/typinganndata/__init__.py
Normal file
0
Lib/test/typinganndata/__init__.py
Normal file
14
Lib/test/typinganndata/ann_module9.py
Normal file
14
Lib/test/typinganndata/ann_module9.py
Normal 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]
|
|
@ -0,0 +1 @@
|
||||||
|
In :mod:`inspect`, fix overeager replacement of "`typing.`" in formatting annotations.
|
Loading…
Add table
Add a link
Reference in a new issue