]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-45662: Fix the repr of InitVar with a type alias to the built-in class (GH-29291)
authorSerhiy Storchaka <storchaka@gmail.com>
Sun, 5 Dec 2021 20:41:58 +0000 (22:41 +0200)
committerGitHub <noreply@github.com>
Sun, 5 Dec 2021 20:41:58 +0000 (22:41 +0200)
For example, InitVar[list[int]].

Lib/dataclasses.py
Lib/test/test_dataclasses.py
Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst [new file with mode: 0644]

index 8643589077a4a89475b20b46e6b29709d2135cdc..da06aa69148b7e0d31f21cd0b6ce1bac30094dc0 100644 (file)
@@ -229,7 +229,7 @@ class InitVar:
         self.type = type
 
     def __repr__(self):
-        if isinstance(self.type, type):
+        if isinstance(self.type, type) and not isinstance(self.type, GenericAlias):
             type_name = self.type.__name__
         else:
             # typing objects, e.g. List[int]
index bcd004f4ec3aa22c9af3f37ae8136f7f0e5f8d08..47075df8d59f3b56cf3768348c9ed9243eb50f1a 100644 (file)
@@ -1126,6 +1126,10 @@ class TestCase(unittest.TestCase):
         self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]')
         self.assertEqual(repr(InitVar[List[int]]),
                          'dataclasses.InitVar[typing.List[int]]')
+        self.assertEqual(repr(InitVar[list[int]]),
+                         'dataclasses.InitVar[list[int]]')
+        self.assertEqual(repr(InitVar[int|str]),
+                         'dataclasses.InitVar[int | str]')
 
     def test_init_var_inheritance(self):
         # Note that this deliberately tests that a dataclass need not
diff --git a/Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst b/Misc/NEWS.d/next/Library/2021-10-28-22-58-14.bpo-45662.sJd7Ir.rst
new file mode 100644 (file)
index 0000000..050b443
--- /dev/null
@@ -0,0 +1,2 @@
+Fix the repr of :data:`dataclasses.InitVar` with a type alias to the
+built-in class, e.g. ``InitVar[list[int]]``.