Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 793cb85

Browse files
samuelcolvinserhiy-storchaka
authored andcommitted
bpo-38431: Fix __repr__ method of InitVar to work with typing objects. (GH-16702)
1 parent 140a7d1 commit 793cb85

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
@@ -206,7 +206,12 @@ def __init__(self, type):
206206
self.type = type
207207

208208
def __repr__(self):
209-
return f'dataclasses.InitVar[{self.type.__name__}]'
209+
if isinstance(self.type, type):
210+
type_name = self.type.__name__
211+
else:
212+
# typing objects, e.g. List[int]
213+
type_name = repr(self.type)
214+
return f'dataclasses.InitVar[{type_name}]'
210215

211216
def __class_getitem__(cls, type):
212217
return InitVar(type)

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)