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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292 | class BaseModel:
"""Common serialize/deserialize with adapters & parsers (enum/datetime/IP support)."""
__schema__: dict[
str, Any
] = {} # field -> BaseModel subclass for nested objects/lists
__enums__: dict[
str, Type[Enum]
] = {} # field -> Enum class (for coercion on from_dict)
# --- Serialization adapters (objects -> JSON scalars) ---
JSON_ADAPTERS: Dict[Type[Any], Callable[[Any], Any]] = {
ipaddress.IPv4Address: str,
ipaddress.IPv6Address: str,
datetime: lambda dt: dt.isoformat().replace("+00:00", "Z")
if dt.tzinfo
else dt.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z"),
}
# --- Deserialization parsers (JSON scalars -> objects) ---
PARSERS: Dict[Type[Any], Callable[[Any], Any]] = {
datetime: lambda s: datetime.fromisoformat(str(s).replace("Z", "+00:00")),
ipaddress.IPv4Address: lambda s: ipaddress.ip_address(s),
ipaddress.IPv6Address: lambda s: ipaddress.ip_address(s),
}
# ---------- to_dict ----------
@staticmethod
def _jsonify(value: Any) -> Any:
if isinstance(value, BaseModel):
return value.to_dict()
if is_dataclass(
value
): # recurse so dataclass fields (e.g., datetime) are adapted
return {
f.name: BaseModel._jsonify(getattr(value, f.name))
for f in fields(value)
}
if isinstance(value, list):
return [BaseModel._jsonify(v) for v in value]
if isinstance(value, Enum):
return (
value.name
) # flip to .value if you prefer the enum values instead of names
for typ, adapter in BaseModel.JSON_ADAPTERS.items():
if isinstance(value, typ):
return adapter(value)
extra = BaseModel._jsonify_extra(value)
if extra is not None:
return extra
return value
@staticmethod
def _jsonify_extra(value: Any) -> Any:
"""Subclass hook: return a JSON-safe object or None to skip."""
return None
def to_dict(self) -> dict[str, Any]:
out: dict[str, Any] = {}
for k, v in self.__dict__.items():
if k.startswith("_"):
continue
out[k] = BaseModel._jsonify(v)
return out
# ---------- from_dict ----------
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
if not isinstance(data, dict):
raise TypeError(f"Expected dict for {cls.__name__}, got {type(data)}")
schema: dict[str, Any] = getattr(cls, "__schema__", {})
enums: dict[str, type[Enum]] = getattr(cls, "__enums__", {})
# <<< use resolved type hints (handles future-annotations and forward refs)
from typing import Union, get_args, get_origin, get_type_hints
ann: dict[str, Any] = get_type_hints(cls)
def _resolve_target_type(t: Any) -> type[Any] | None:
# already a concrete class?
if isinstance(t, type):
return t
origin = get_origin(t)
if origin is None:
return None
# Optional/Union[...] → pick the first concrete class (e.g., datetime)
if origin is Union:
for arg in get_args(t):
if isinstance(arg, type):
return arg
return None
return None
def coerce_scalar(key: str, val: Any) -> Any:
if val is None:
return None
# Enums (opt-in via __enums__)
if key in enums:
et = enums[key]
if isinstance(val, et):
return val
if isinstance(val, str):
try:
return et[val] # by NAME
except KeyError:
for m in et:
if m.value == val: # by VALUE
return m
raise TypeError(
f"Cannot coerce {val!r} to {et.__name__} for field {key}"
)
# Parsers (datetime, IPs, etc.) based on resolved annotation
target = _resolve_target_type(ann.get(key))
if target is not None:
parser = BaseModel.PARSERS.get(target)
if parser is not None and not isinstance(val, target):
return parser(val)
return val
# 1) Normalize nested fields and coerce direct scalars
normalized: dict[str, Any] = {}
for key, val in data.items():
if key in schema:
subcls = schema[key]
if isinstance(subcls, str):
resolved: object | None = None
# Prefer resolving from type hints (already get_type_hints(cls) above)
hinted = ann.get(key)
if hinted is not None:
origin = get_origin(hinted)
args = get_args(hinted)
# list[T] / set[T] / tuple[T,...]
if origin in (list, set, tuple) and args:
if isinstance(args[0], type):
resolved = args[0]
# direct T
elif isinstance(hinted, type):
resolved = hinted
# Fallback: resolve from the module where cls is defined
if resolved is None:
mod = sys.modules.get(cls.__module__)
if mod is not None and hasattr(mod, subcls):
cand = getattr(mod, subcls)
if isinstance(cand, type):
resolved = cand
if resolved is None:
raise TypeError(
f"Could not resolve schema type '{subcls}' for field '{key}' on {cls.__name__}"
)
subcls = resolved
if val is None:
normalized[key] = None
continue
if isinstance(val, list):
out_list: list[Any] = []
for v in val:
if isinstance(v, dict):
out_list.append(subcls.from_dict(v))
elif isinstance(v, subcls):
out_list.append(v)
else:
raise TypeError(
f"Unexpected type in list for {key}: {type(v)}"
)
normalized[key] = out_list
elif isinstance(val, dict):
normalized[key] = subcls.from_dict(val)
elif isinstance(val, subcls):
normalized[key] = val
else:
raise TypeError(f"Unexpected type for {key}: {type(val)}")
else:
normalized[key] = coerce_scalar(key, val)
# 2) Filter kwargs to __init__
sig = inspect.signature(cls)
accepted = {
p.name
for p in sig.parameters.values()
if p.kind
in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
}
ctor_kwargs = {k: v for k, v in normalized.items() if k in accepted}
# 3) Construct
obj = cls(**ctor_kwargs)
# 4) Set remaining attributes
for k, v in normalized.items():
if k not in ctor_kwargs:
setattr(obj, k, v)
# 5) Final safety pass: coerce any annotated scalars left as strings/etc.
for k, annot in ann.items():
if not hasattr(obj, k):
continue
cur = getattr(obj, k)
if cur is None:
continue
# skip nested/containers
if isinstance(cur, (BaseModel, list, dict)):
continue
# Enums again if needed
if k in enums and isinstance(cur, str):
et = enums[k]
try:
setattr(obj, k, et[cur]) # by NAME
continue
except KeyError:
for m in et:
if m.value == cur: # by VALUE
setattr(obj, k, m)
break
continue
# Parsers again with resolved type
target = _resolve_target_type(annot)
if target is not None:
parser = BaseModel.PARSERS.get(target)
if parser is not None and not isinstance(cur, target):
try:
setattr(obj, k, parser(cur))
except Exception:
pass
return obj
def __eq__(self, other: object) -> bool:
return isinstance(other, self.__class__) and self.to_dict() == other.to_dict()
def __hash__(self) -> int:
return hash(json.dumps(self.to_dict(), sort_keys=True))
|