Skip to content

Commit ee8ecce

Browse files
committed
ch10: add @DataClass decorator: code generation
1 parent 25a4c27 commit ee8ecce

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import inspect
2+
3+
4+
def build_dataclass_init[T](cls: type[T]) -> str:
5+
annotations = inspect.get_annotations(cls)
6+
7+
args: list[str] = ["self"]
8+
body: list[str] = []
9+
10+
for name, type in annotations.items():
11+
args.append(f"{name}: {type.__name__}")
12+
body.append(f" self.{name} = {name}")
13+
14+
return "def __init__({}) -> None:\n{}".format(
15+
", ".join(args),
16+
"\n".join(body),
17+
)

0 commit comments

Comments
 (0)