summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/inspect.py5
-rw-r--r--Lib/test/test_inspect.py7
-rw-r--r--Lib/test/typinganndata/__init__.py0
-rw-r--r--Lib/test/typinganndata/ann_module9.py14
4 files changed, 25 insertions, 1 deletions
diff --git a/Lib/inspect.py b/Lib/inspect.py
index cbc0632..5f7574c 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -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):
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index be9f29e..c030be7 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -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):
diff --git a/Lib/test/typinganndata/__init__.py b/Lib/test/typinganndata/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/Lib/test/typinganndata/__init__.py
diff --git a/Lib/test/typinganndata/ann_module9.py b/Lib/test/typinganndata/ann_module9.py
new file mode 100644
index 0000000..9522173
--- /dev/null
+++ b/Lib/test/typinganndata/ann_module9.py
@@ -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]