]> granicus.if.org Git - python/commitdiff
bpo-33569 Preserve type information with dataclasses.InitVar (GH-8927)
authorAugusto Hack <hack.augusto@gmail.com>
Mon, 3 Jun 2019 02:14:48 +0000 (23:14 -0300)
committerEric V. Smith <ericvsmith@users.noreply.github.com>
Mon, 3 Jun 2019 02:14:48 +0000 (22:14 -0400)
Lib/dataclasses.py
Lib/test/test_dataclasses.py
Misc/NEWS.d/next/Library/2018-08-28-03-00-12.bpo-33569.45YlGG.rst [new file with mode: 0644]

index 75113f123b3af1d48bf0057487788a7193459131..b035cbb809f848a29e3d82bcb879e89f1b23c1c2 100644 (file)
@@ -201,10 +201,16 @@ _MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')
 
 class _InitVarMeta(type):
     def __getitem__(self, params):
-        return self
+        return InitVar(params)
 
 class InitVar(metaclass=_InitVarMeta):
-    pass
+    __slots__ = ('type', )
+
+    def __init__(self, type):
+        self.type = type
+
+    def __repr__(self):
+        return f'dataclasses.InitVar[{self.type.__name__}]'
 
 
 # Instances of Field are only ever created from within this module,
@@ -586,7 +592,8 @@ def _is_classvar(a_type, typing):
 def _is_initvar(a_type, dataclasses):
     # The module we're checking against is the module we're
     # currently in (dataclasses.py).
-    return a_type is dataclasses.InitVar
+    return (a_type is dataclasses.InitVar
+            or type(a_type) is dataclasses.InitVar)
 
 
 def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
index 867210688f5737f8d8034d26492be73e557e5a1c..53e8443c2adf17f1b461704a5e3a25759cf62e16 100755 (executable)
@@ -1097,6 +1097,12 @@ class TestCase(unittest.TestCase):
         c = C(init_param=10)
         self.assertEqual(c.x, 20)
 
+    def test_init_var_preserve_type(self):
+        self.assertEqual(InitVar[int].type, int)
+
+        # Make sure the repr is correct.
+        self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]')
+
     def test_init_var_inheritance(self):
         # Note that this deliberately tests that a dataclass need not
         #  have a __post_init__ function if it has an InitVar field.
diff --git a/Misc/NEWS.d/next/Library/2018-08-28-03-00-12.bpo-33569.45YlGG.rst b/Misc/NEWS.d/next/Library/2018-08-28-03-00-12.bpo-33569.45YlGG.rst
new file mode 100644 (file)
index 0000000..adafa28
--- /dev/null
@@ -0,0 +1 @@
+dataclasses.InitVar: Exposes the type used to create the init var.