Skip to content

Commit d9fbabb

Browse files
committed
ch10: add @DataClass decorator: implement decorator
1 parent ee8ecce commit d9fbabb

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

chapter10-using-types-for-safety-and-inspection/dataclasses2.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import inspect
2+
import sys
3+
from typing import dataclass_transform
24

35

46
def build_dataclass_init[T](cls: type[T]) -> str:
@@ -15,3 +17,15 @@ def build_dataclass_init[T](cls: type[T]) -> str:
1517
", ".join(args),
1618
"\n".join(body),
1719
)
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

Comments
 (0)