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 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
|
from dataclasses import dataclass, field
from typing import AbstractSet, Any, Callable, Dict, Optional, Tuple, Union
from apischema.conversions.utils import Converter
from apischema.fields import FIELDS_SET_ATTR
from apischema.serialization.errors import TypeCheckError
from apischema.types import AnyType, Undefined
from apischema.utils import Lazy
class SerializationMethod:
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
raise NotImplementedError
class IdentityMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return obj
class ListMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return list(obj)
class DictMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return dict(obj)
class StrMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return str(obj)
class IntMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return int(obj)
class BoolMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return bool(obj)
class FloatMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return float(obj)
class NoneMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return None
@dataclass
class RecMethod(SerializationMethod):
lazy: Lazy[SerializationMethod]
method: Optional[SerializationMethod] = field(init=False)
def __post_init__(self):
self.method = None
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
if self.method is None:
self.method = self.lazy()
return self.method.serialize(obj)
@dataclass
class AnyMethod(SerializationMethod):
factory: Callable[[AnyType], SerializationMethod]
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
method: SerializationMethod = self.factory(
obj.__class__
) # tmp variable for substitution
return method.serialize(obj, path)
class Fallback:
def fall_back(self, obj: Any, path: Union[int, str, None]) -> Any:
raise NotImplementedError
@dataclass
class NoFallback(Fallback):
tp: AnyType
def fall_back(self, obj: Any, path: Union[int, str, None]) -> Any:
raise TypeCheckError(
f"Expected {self.tp}, found {obj.__class__}",
[path] if path is not None else [],
)
@dataclass
class AnyFallback(Fallback):
any_method: SerializationMethod
def fall_back(self, obj: Any, key: Union[int, str, None]) -> Any:
return self.any_method.serialize(obj, key)
@dataclass
class TypeCheckIdentityMethod(SerializationMethod):
expected: AnyType # `type` would require exact match (i.e. no EnumMeta)
fallback: Fallback
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return (
obj
if isinstance(obj, self.expected)
else self.fallback.fall_back(obj, path)
)
@dataclass
class TypeCheckMethod(SerializationMethod):
method: SerializationMethod
expected: AnyType # `type` would require exact match (i.e. no EnumMeta)
fallback: Fallback
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
if isinstance(obj, self.expected):
try:
return self.method.serialize(obj)
except TypeCheckError as err:
if path is None:
raise
raise TypeCheckError(err.msg, [path, *err.loc])
else:
return self.fallback.fall_back(obj, path)
@dataclass
class CollectionCheckOnlyMethod(SerializationMethod):
value_method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
for i, elt in enumerate(obj):
self.value_method.serialize(elt, i)
return obj
@dataclass
class CollectionMethod(SerializationMethod):
value_method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return [self.value_method.serialize(elt, i) for i, elt in enumerate(obj)]
class ValueMethod(SerializationMethod):
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return obj.value
@dataclass
class EnumMethod(SerializationMethod):
any_method: AnyMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return self.any_method.serialize(obj.value)
@dataclass
class MappingCheckOnlyMethod(SerializationMethod):
key_method: SerializationMethod
value_method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
for key, value in obj.items():
self.key_method.serialize(key, key)
self.value_method.serialize(value, key)
return obj
@dataclass
class MappingMethod(SerializationMethod):
key_method: SerializationMethod
value_method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return {
self.key_method.serialize(key, key): self.value_method.serialize(value, key)
for key, value in obj.items()
}
@dataclass
class BaseField:
name: str
alias: str
def update_result(self, obj: Any, result: dict):
raise NotImplementedError
@dataclass
class IdentityField(BaseField):
def update_result(self, obj: Any, result: dict):
result[self.alias] = getattr(obj, self.name)
@dataclass
class SimpleField(BaseField):
method: SerializationMethod
def update_result(self, obj: Any, result: dict):
result[self.alias] = self.method.serialize(getattr(obj, self.name), self.alias)
@dataclass
class ComplexField(BaseField):
method: SerializationMethod
typed_dict: bool
required: bool
exclude_unset: bool
skip_if: Optional[Callable]
undefined: bool
skip_none: bool
skip_default: bool
default_value: Any # https://github.com/cython/cython/issues/4383
skippable: bool = field(init=False)
def __post_init__(self):
self.skippable = bool(
self.skip_if or self.undefined or self.skip_none or self.skip_default
)
def update_result(self, obj: Any, result: dict):
if (
(self.required or self.name in obj)
if self.typed_dict
else (not self.exclude_unset or self.name in getattr(obj, FIELDS_SET_ATTR))
):
value = obj[self.name] if self.typed_dict else getattr(obj, self.name)
if not self.skippable or not (
(self.skip_if is not None and self.skip_if(value))
or (self.undefined and value is Undefined)
or (self.skip_none and value is None)
or (self.skip_default and value == self.default_value)
):
if self.alias is not None:
result[self.alias] = self.method.serialize(value, self.alias)
else:
result.update(self.method.serialize(value, self.alias))
@dataclass
class SerializedField(BaseField):
func: Callable[[Any], Any]
undefined: bool
skip_none: bool
method: SerializationMethod
def update_result(self, obj: Any, result: dict):
value = self.func(obj)
if not (self.undefined and value is Undefined) and not (
self.skip_none and value is None
):
result[self.alias] = self.method.serialize(value, self.alias)
@dataclass
class SimpleObjectMethod(SerializationMethod):
fields: Tuple[str, ...]
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return {name: getattr(obj, name) for name in self.fields}
@dataclass
class ObjectMethod(SerializationMethod):
fields: Tuple[BaseField, ...]
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
result: dict = {}
for field in self.fields:
field.update_result(obj, result)
return result
@dataclass
class ObjectAdditionalMethod(ObjectMethod):
field_names: AbstractSet[str]
any_method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
result: dict = super().serialize(obj)
for key, value in obj.items():
if isinstance(key, str) and not (key in self.field_names or key in result):
result[key] = self.any_method.serialize(value, key)
return result
@dataclass
class TupleCheckOnlyMethod(SerializationMethod):
nb_elts: int
elt_methods: Tuple[SerializationMethod, ...]
def serialize(self, obj: tuple, path: Union[int, str, None] = None) -> Any:
for i, method in enumerate(self.elt_methods):
method.serialize(obj[i], i)
return obj
@dataclass
class TupleMethod(SerializationMethod):
nb_elts: int
elt_methods: Tuple[SerializationMethod, ...]
def serialize(self, obj: tuple, path: Union[int, str, None] = None) -> Any:
elts: list = [None] * len(self.elt_methods)
for i, method in enumerate(self.elt_methods):
elts[i] = method.serialize(obj[i], i)
return elts
@dataclass
class CheckedTupleMethod(SerializationMethod):
nb_elts: int
method: SerializationMethod
def serialize(self, obj: tuple, path: Union[int, str, None] = None) -> Any:
if not len(obj) == self.nb_elts:
raise TypeError(f"Expected {self.nb_elts}-tuple, found {len(obj)}-tuple")
return self.method.serialize(obj)
# There is no need of an OptionalIdentityMethod because it would mean that all methods
# are IdentityMethod, which gives IdentityMethod.
@dataclass
class OptionalMethod(SerializationMethod):
value_method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return self.value_method.serialize(obj, path) if obj is not None else None
@dataclass
class UnionAlternative(SerializationMethod):
cls: AnyType # `type` would require exact match (i.e. no EnumMeta)
method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return self.method.serialize(obj, path)
@dataclass
class DiscriminatedAlternative(UnionAlternative):
alias: str
key: str
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
res = super().serialize(obj, path)
if isinstance(res, dict) and self.alias not in res:
res[self.alias] = self.key
return res
@dataclass
class UnionMethod(SerializationMethod):
alternatives: Tuple[UnionAlternative, ...]
fallback: Fallback
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
for alternative in self.alternatives:
if isinstance(obj, alternative.cls):
try:
return alternative.serialize(obj, path)
except Exception:
pass
return self.fallback.fall_back(obj, path)
@dataclass
class WrapperMethod(SerializationMethod):
wrapped: Callable[[Any], Any]
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return self.wrapped(obj)
@dataclass
class ConversionMethod(SerializationMethod):
converter: Converter
method: SerializationMethod
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
return self.method.serialize(self.converter(obj))
@dataclass
class DiscriminateTypedDict(SerializationMethod):
field_name: str
mapping: Dict[str, SerializationMethod]
fallback: Fallback
def serialize(self, obj: Any, path: Union[int, str, None] = None) -> Any:
try:
method: SerializationMethod = self.mapping[obj[self.field_name]]
except Exception:
return self.fallback.fall_back(obj, path)
return method.serialize(obj, path)
def identity(arg: Any) -> Any:
return arg
|