We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ee8ecce commit d9fbabbCopy full SHA for d9fbabb
chapter10-using-types-for-safety-and-inspection/dataclasses2.py
@@ -1,4 +1,6 @@
1
import inspect
2
+import sys
3
+from typing import dataclass_transform
4
5
6
def build_dataclass_init[T](cls: type[T]) -> str:
@@ -15,3 +17,15 @@ def build_dataclass_init[T](cls: type[T]) -> str:
15
17
", ".join(args),
16
18
"\n".join(body),
19
)
20
+
21
22
+@dataclass_transform()
23
+def dataclass[T](cls: type[T]) -> type[T]:
24
+ sourcecode = build_dataclass_init(cls)
25
26
+ globals = sys.modules[cls.__module__].__dict__
27
+ locals = {}
28
+ exec(sourcecode, globals, locals)
29
30
+ cls.__init__ = locals["__init__"]
31
+ return cls
0 commit comments