-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_dataclass_like.py
More file actions
150 lines (107 loc) · 3.2 KB
/
test_dataclass_like.py
File metadata and controls
150 lines (107 loc) · 3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from typing import (
Callable,
Literal,
ReadOnly,
TypedDict,
Never,
)
import typemap_extensions as typing
class FieldArgs(TypedDict, total=False):
default: ReadOnly[object]
class Field[T: FieldArgs](typing.InitField[T]):
pass
####
# TODO: Should this go into the stdlib?
type GetFieldItem[T, K] = typing.GetMemberType[
typing.GetArg[T, typing.InitField, Literal[0]], K
]
# Extract the default type from an Init field.
# If it is a Field, then we try pulling out the "default" field,
# otherwise we return the type itself.
type GetDefault[Init] = (
GetFieldItem[Init, Literal["default"]]
if typing.IsAssignable[Init, Field]
else Init
)
# TODO: what could we do to make dataclass_ish work at runtime?
# Begin PEP section: dataclass like __init__
"""
``InitFnType`` generates a ``Member`` for a new ``__init__`` function
based on iterating over all attributes.
``GetDefault`` here is borrowed from our FastAPI-like example above.
"""
# Generate the Member field for __init__ for a class
type InitFnType[T] = typing.Member[
Literal["__init__"],
Callable[
typing.Params[
typing.Param[Literal["self"], T],
*[
typing.Param[
p.name,
p.type,
# All arguments are keyword-only
# It takes a default if a default is specified in the class
Literal["keyword"]
if typing.IsAssignable[
GetDefault[p.init],
Never,
]
else Literal["keyword", "default"],
]
for p in typing.Iter[typing.Attrs[T]]
],
],
None,
],
Literal["ClassVar"],
]
type AddInit[T] = typing.NewProtocol[
InitFnType[T],
*[x for x in typing.Iter[typing.Members[T]]],
]
"""
``UpdateClass`` can then be used to create a class decorator (a la
``@dataclass``) adds a new ``__init__`` method to a class.
"""
def dataclass_ish[T](
cls: type[T],
) -> typing.UpdateClass[
# Add the computed __init__ function
InitFnType[T],
]:
raise NotImplementedError
"""
Or to create a base class (a la Pydantic) that does.
"""
class Model:
def __init_subclass__[T](
cls: type[T],
) -> typing.UpdateClass[
# Add the computed __init__ function
InitFnType[T],
]:
pass
# End PEP section
class Hero(Model):
id: int | None = None
name: str
age: int | None = Field(default=None)
secret_name: str
#######
import textwrap
from typemap.type_eval import eval_typing
from typemap.type_eval import format_helper
def test_dataclass_like_1():
tgt = eval_typing(Hero)
fmt = format_helper.format_class(tgt)
assert fmt == textwrap.dedent("""\
class Hero:
id: int | None = None
name: str
age: int | None = Field(default=None)
secret_name: str
@classmethod
def __init_subclass__[T](cls: type[T]) -> typemap.typing.UpdateClass[InitFnType[T]]: ...
def __init__(self: Self, *, id: int | None = ..., name: str, age: int | None = ..., secret_name: str) -> None: ...
""")