[Python-checkins] bpo-38431: Fix __repr__ method of InitVar to work with typing objects. (GH-16702)
Miss Islington (bot)
webhook-mailer at python.org
Sun Oct 13 08:04:08 EDT 2019
https://github.com/python/cpython/commit/6da52ac411947d1a7958bbad831fcf8dfc8c95fe
commit: 6da52ac411947d1a7958bbad831fcf8dfc8c95fe
branch: 3.8
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2019-10-13T05:04:05-07:00
summary:
bpo-38431: Fix __repr__ method of InitVar to work with typing objects. (GH-16702)
(cherry picked from commit 793cb85437299a3da3d74fe65480d720af330cbb)
Co-authored-by: Samuel Colvin <samcolvin at gmail.com>
files:
A Misc/NEWS.d/next/Library/2019-10-10-16-53-00.bpo-38431.d5wzNp.rst
M Lib/dataclasses.py
M Lib/test/test_dataclasses.py
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index 2f0e5ff0b6e03..391f32e11d52a 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -210,7 +210,12 @@ def __init__(self, type):
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,
diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py
index 0885c9798fe68..b018133cf2302 100755
--- a/Lib/test/test_dataclasses.py
+++ b/Lib/test/test_dataclasses.py
@@ -1102,6 +1102,8 @@ def test_init_var_preserve_type(self):
# 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
index 0000000000000..c2f860d804c13
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-10-10-16-53-00.bpo-38431.d5wzNp.rst
@@ -0,0 +1 @@
+Fix ``__repr__`` method for :class:`dataclasses.InitVar` to support typing objects, patch by Samuel Colvin.
More information about the Python-checkins
mailing list