]> granicus.if.org Git - python/commitdiff
bpo-38431: Fix __repr__ method of InitVar to work with typing objects. (GH-16702)
authorSamuel Colvin <samcolvin@gmail.com>
Sun, 13 Oct 2019 11:45:36 +0000 (12:45 +0100)
committerSerhiy Storchaka <storchaka@gmail.com>
Sun, 13 Oct 2019 11:45:36 +0000 (14:45 +0300)
Lib/dataclasses.py
Lib/test/test_dataclasses.py
Misc/NEWS.d/next/Library/2019-10-10-16-53-00.bpo-38431.d5wzNp.rst [new file with mode: 0644]

index 9135b07c9f259a914f7c1d574dc8e87855a3b214..91c1f6f80fc68465d9d1bc93ad2448bd42c6ee90 100644 (file)
@@ -206,7 +206,12 @@ class InitVar:
         self.type = type
 
     def __repr__(self):
-        return f'dataclasses.InitVar[{self.type.__name__}]'
+        if isinstance(self.type, type):
+            type_name = self.type.__name__
+        else:
+            # typing objects, e.g. List[int]
+            type_name = repr(self.type)
+        return f'dataclasses.InitVar[{type_name}]'
 
     def __class_getitem__(cls, type):
         return InitVar(type)
index 037bf4c22142798b7ce0df66cc24a228691432bc..238335e7d9edad0650de2719d12849ea601ca9a0 100644 (file)
@@ -1102,6 +1102,8 @@ class TestCase(unittest.TestCase):
 
         # Make sure the repr is correct.
         self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]')
+        self.assertEqual(repr(InitVar[List[int]]),
+                         'dataclasses.InitVar[typing.List[int]]')
 
     def test_init_var_inheritance(self):
         # Note that this deliberately tests that a dataclass need not
diff --git a/Misc/NEWS.d/next/Library/2019-10-10-16-53-00.bpo-38431.d5wzNp.rst b/Misc/NEWS.d/next/Library/2019-10-10-16-53-00.bpo-38431.d5wzNp.rst
new file mode 100644 (file)
index 0000000..c2f860d
--- /dev/null
@@ -0,0 +1 @@
+Fix ``__repr__`` method for :class:`dataclasses.InitVar` to support typing objects, patch by Samuel Colvin.