Skip to content

Commit e045143

Browse files
committed
bpo-38431: fix dataclasses.InitVar.__repr__
Fix repr method of InitVar to work with typing objects.
1 parent b6e0fc7 commit e045143

4 files changed

Lines changed: 13 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+
try:
210+
type_name = self.type.__name__
211+
except AttributeError:
212+
# typing objects, e.g. Union
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: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2883,6 +2883,11 @@ class C:
28832883
# x is not an InitVar, so there will be a member x.
28842884
self.assertEqual(C(10).x, 10)
28852885

2886+
def test_initvar_repr(self):
2887+
self.assertEqual(repr(InitVar[str]), 'dataclasses.InitVar[str]')
2888+
self.assertEqual(repr(InitVar[Optional[str]]),
2889+
'dataclasses.InitVar[typing.Union[str, NoneType]]')
2890+
28862891
def test_classvar_module_level_import(self):
28872892
from test import dataclass_module_1
28882893
from test import dataclass_module_1_str

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,7 @@ Benjamin Collar
321321
Jeffery Collins
322322
Robert Collins
323323
Paul Colomiets
324+
Samuel Colvin
324325
Christophe Combelles
325326
Geremy Condra
326327
Denver Coneybeare
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.

0 commit comments

Comments
 (0)