]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-38431: Fix __repr__ method of InitVar to work with typing objects. (GH-16702)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 13 Oct 2019 12:04:05 +0000 (05:04 -0700)
committerGitHub <noreply@github.com>
Sun, 13 Oct 2019 12:04:05 +0000 (05:04 -0700)
(cherry picked from commit 793cb85437299a3da3d74fe65480d720af330cbb)

Co-authored-by: Samuel Colvin <samcolvin@gmail.com>
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 2f0e5ff0b6e039aeac9318c6b2c40ec2f5a4aa7a..391f32e11d52a18ee9fe864f2bd78a2ffec36038 100644 (file)
@@ -210,7 +210,12 @@ class InitVar(metaclass=_InitVarMeta):
         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}]'
 
 
 # Instances of Field are only ever created from within this module,
index 0885c9798fe68ab1ac5c466261e5c9f0731bb4bd..b018133cf23025ab776c0b1384d973b32c3b37c4 100755 (executable)
@@ -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.