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

Skip to content

Commit 01ee12b

Browse files
hackaugustoericvsmith
authored andcommitted
bpo-33569 Preserve type information with dataclasses.InitVar (GH-8927)
1 parent 0025350 commit 01ee12b

3 files changed

Lines changed: 17 additions & 3 deletions

File tree

Lib/dataclasses.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,16 @@ def __repr__(self):
201201

202202
class _InitVarMeta(type):
203203
def __getitem__(self, params):
204-
return self
204+
return InitVar(params)
205205

206206
class InitVar(metaclass=_InitVarMeta):
207-
pass
207+
__slots__ = ('type', )
208+
209+
def __init__(self, type):
210+
self.type = type
211+
212+
def __repr__(self):
213+
return f'dataclasses.InitVar[{self.type.__name__}]'
208214

209215

210216
# Instances of Field are only ever created from within this module,
@@ -586,7 +592,8 @@ def _is_classvar(a_type, typing):
586592
def _is_initvar(a_type, dataclasses):
587593
# The module we're checking against is the module we're
588594
# currently in (dataclasses.py).
589-
return a_type is dataclasses.InitVar
595+
return (a_type is dataclasses.InitVar
596+
or type(a_type) is dataclasses.InitVar)
590597

591598

592599
def _is_type(annotation, cls, a_module, a_type, is_type_predicate):

Lib/test/test_dataclasses.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1097,6 +1097,12 @@ def __post_init__(self, init_param):
10971097
c = C(init_param=10)
10981098
self.assertEqual(c.x, 20)
10991099

1100+
def test_init_var_preserve_type(self):
1101+
self.assertEqual(InitVar[int].type, int)
1102+
1103+
# Make sure the repr is correct.
1104+
self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]')
1105+
11001106
def test_init_var_inheritance(self):
11011107
# Note that this deliberately tests that a dataclass need not
11021108
# have a __post_init__ function if it has an InitVar field.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
dataclasses.InitVar: Exposes the type used to create the init var.

0 commit comments

Comments
 (0)