Skip to content

Commit 6da52ac

Browse files
bpo-38431: Fix __repr__ method of InitVar to work with typing objects. (GH-16702)
(cherry picked from commit 793cb85) Co-authored-by: Samuel Colvin <samcolvin@gmail.com>
1 parent ba44ea6 commit 6da52ac

3 files changed

Lines changed: 9 additions & 1 deletion

File tree

Lib/dataclasses.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,12 @@ def __init__(self, type):
210210
self.type = type
211211

212212
def __repr__(self):
213-
return f'dataclasses.InitVar[{self.type.__name__}]'
213+
if isinstance(self.type, type):
214+
type_name = self.type.__name__
215+
else:
216+
# typing objects, e.g. List[int]
217+
type_name = repr(self.type)
218+
return f'dataclasses.InitVar[{type_name}]'
214219

215220

216221
# Instances of Field are only ever created from within this module,

Lib/test/test_dataclasses.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1102,6 +1102,8 @@ def test_init_var_preserve_type(self):
11021102

11031103
# Make sure the repr is correct.
11041104
self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]')
1105+
self.assertEqual(repr(InitVar[List[int]]),
1106+
'dataclasses.InitVar[typing.List[int]]')
11051107

11061108
def test_init_var_inheritance(self):
11071109
# Note that this deliberately tests that a dataclass need not
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``__repr__`` method for :class:`dataclasses.InitVar` to support typing objects, patch by Samuel Colvin.

0 commit comments

Comments
 (0)