|
10 | 10 | annotated ``type[Family]``. A family whose boundary spelling is not its |
11 | 11 | registry (for example one resolved through an active subset) registers its own |
12 | 12 | decoder on its metaclass. |
| 13 | +
|
| 14 | +A dataclass field whose declared type admits several classes (``MemberFamily``: |
| 15 | +a union of dataclasses, an abstract dataclass, or a registered class) holds its |
| 16 | +value as ``{tag: fields}``. The tag is the member's registry key when its |
| 17 | +metaclass registers it and its class name otherwise, so the stored form names |
| 18 | +the class instead of leaving the decoder to guess it from the fields present. |
13 | 19 | """ |
14 | 20 |
|
15 | 21 | from __future__ import annotations |
16 | 22 |
|
17 | 23 | import inspect |
18 | | -from collections.abc import Callable, Mapping |
| 24 | +from abc import ABC, abstractmethod |
| 25 | +from collections.abc import Callable, Mapping, Sequence, Set |
19 | 26 | from dataclasses import dataclass, fields, is_dataclass |
20 | 27 | from enum import Enum |
21 | 28 | from functools import singledispatch |
22 | 29 | from pathlib import Path |
23 | | -from typing import ForwardRef, TypeAlias |
| 30 | +from typing import Annotated, ForwardRef, TypeAlias, get_args, get_origin |
| 31 | +from weakref import WeakKeyDictionary |
24 | 32 |
|
25 | 33 | from metaclass_registry import AutoRegisterMeta |
26 | 34 |
|
| 35 | +from .annotation_types import is_union_type, resolved_class_annotations |
27 | 36 | from .choices import AnnotationChoices |
28 | 37 | from .signature_analyzer import signature_analysis_target |
29 | 38 |
|
|
40 | 49 | JsonObject: TypeAlias = Mapping[str, JsonValue] |
41 | 50 |
|
42 | 51 |
|
| 52 | +_FIELD_TYPES_BY_DATACLASS: WeakKeyDictionary[type, Mapping[str, object]] = WeakKeyDictionary() |
| 53 | + |
| 54 | + |
| 55 | +def _declared_field_types(owner: type) -> Mapping[str, object]: |
| 56 | + if owner not in _FIELD_TYPES_BY_DATACLASS: |
| 57 | + try: |
| 58 | + _FIELD_TYPES_BY_DATACLASS[owner] = resolved_class_annotations(owner) |
| 59 | + except NameError as error: |
| 60 | + raise TypeError( |
| 61 | + f"{owner.__qualname__} cannot be projected: a field type does not resolve " |
| 62 | + f"at run time ({error}). A field's declared type decides its stored form, " |
| 63 | + "so import the name outside TYPE_CHECKING." |
| 64 | + ) from error |
| 65 | + return _FIELD_TYPES_BY_DATACLASS[owner] |
| 66 | + |
| 67 | + |
43 | 68 | def _jsonable_dataclass(value: object) -> JsonValue: |
44 | | - """Project fields without ``asdict`` deep-copying immutable containers.""" |
| 69 | + """Project each field by its declared type, without ``asdict`` deep copies.""" |
45 | 70 |
|
| 71 | + declared_types = _declared_field_types(type(value)) |
46 | 72 | return { |
47 | | - declared_field.name: to_jsonable(getattr(value, declared_field.name)) |
| 73 | + declared_field.name: _jsonable_as_declared( |
| 74 | + declared_types[declared_field.name], getattr(value, declared_field.name) |
| 75 | + ) |
48 | 76 | for declared_field in fields(value) |
49 | 77 | } |
50 | 78 |
|
51 | 79 |
|
| 80 | +def _projects_by_declared_fields(value: object) -> bool: |
| 81 | + """Whether ``to_jsonable`` writes ``value`` as its dataclass fields. |
| 82 | +
|
| 83 | + A type with its own registered projection owns its whole stored form, |
| 84 | + including how that form names the class. |
| 85 | + """ |
| 86 | + |
| 87 | + return ( |
| 88 | + is_dataclass(value) |
| 89 | + and not isinstance(value, type) |
| 90 | + and to_jsonable.dispatch(type(value)) in (to_jsonable.registry[object], _jsonable_callable) |
| 91 | + ) |
| 92 | + |
| 93 | + |
| 94 | +def _jsonable_as_declared(annotation: object, value: object) -> JsonValue: |
| 95 | + """Project ``value`` as a field declared ``annotation`` stores it. |
| 96 | +
|
| 97 | + The declaration is followed through optional, annotated and container types |
| 98 | + to the places where it admits several classes; a value there is wrapped in |
| 99 | + its member tag. Everything else projects by its own type. |
| 100 | + """ |
| 101 | + |
| 102 | + if value is None: |
| 103 | + return None |
| 104 | + origin = get_origin(annotation) |
| 105 | + if origin is Annotated: |
| 106 | + return _jsonable_as_declared(get_args(annotation)[0], value) |
| 107 | + family = MemberFamily.declared_by(annotation) |
| 108 | + if family is not None and _projects_by_declared_fields(value): |
| 109 | + return {family.tag_of(type(value)): to_jsonable(value)} |
| 110 | + if is_union_type(annotation): |
| 111 | + arms = tuple( |
| 112 | + arm |
| 113 | + for arm in get_args(annotation) |
| 114 | + if isinstance(runtime_class := get_origin(arm) or arm, type) |
| 115 | + and runtime_class is not type(None) |
| 116 | + and isinstance(value, runtime_class) |
| 117 | + ) |
| 118 | + return _jsonable_as_declared(arms[0], value) if len(arms) == 1 else to_jsonable(value) |
| 119 | + item_types = get_args(annotation) |
| 120 | + if ( |
| 121 | + isinstance(origin, type) |
| 122 | + and item_types |
| 123 | + and isinstance(value, origin) |
| 124 | + and not isinstance(value, (str, bytes, bytearray)) |
| 125 | + ): |
| 126 | + if issubclass(origin, Mapping) and len(item_types) == 2: |
| 127 | + return { |
| 128 | + str(to_jsonable(key)): _jsonable_as_declared(item_types[1], item) |
| 129 | + for key, item in value.items() |
| 130 | + } |
| 131 | + if origin is tuple and Ellipsis not in item_types and len(item_types) == len(value): |
| 132 | + return [ |
| 133 | + _jsonable_as_declared(item_type, item) for item_type, item in zip(item_types, value) |
| 134 | + ] |
| 135 | + if issubclass(origin, (Sequence, Set)): |
| 136 | + return [_jsonable_as_declared(item_types[0], item) for item in value] |
| 137 | + return to_jsonable(value) |
| 138 | + |
| 139 | + |
52 | 140 | @singledispatch |
53 | 141 | def to_jsonable(value: object) -> JsonValue: |
54 | 142 | """Project dataclasses and registered values into JSON-native data.""" |
@@ -100,7 +188,7 @@ def _jsonable_registered_type(value: AutoRegisterMeta) -> JsonValue: |
100 | 188 | ) |
101 | 189 | if declaring_owner is None: |
102 | 190 | raise TypeError( |
103 | | - f"Registered type {value.__qualname__} has no declared " f"{key_attribute!r} key." |
| 191 | + f"Registered type {value.__qualname__} has no declared {key_attribute!r} key." |
104 | 192 | ) |
105 | 193 | key = vars(declaring_owner)[key_attribute] |
106 | 194 | if key is None: |
@@ -149,6 +237,146 @@ def _registered_class_from_registry(family: AutoRegisterMeta, key: JsonValue) -> |
149 | 237 | return matches[0] |
150 | 238 |
|
151 | 239 |
|
| 240 | +class MemberFamily(ABC): |
| 241 | + """The classes a declared field type admits, each named by one tag. |
| 242 | +
|
| 243 | + A value of such a field is stored as ``{tag: fields}``. Three declarations |
| 244 | + form a family: a union with two or more dataclass members, an abstract |
| 245 | + dataclass (its concrete subclasses are the members) and a class registered |
| 246 | + by ``AutoRegisterMeta`` (the registry's classes are the members). |
| 247 | + """ |
| 248 | + |
| 249 | + @staticmethod |
| 250 | + def declared_by(annotation: object) -> MemberFamily | None: |
| 251 | + """The family ``annotation`` declares, or None when it names one class.""" |
| 252 | + |
| 253 | + if is_union_type(annotation): |
| 254 | + members = tuple( |
| 255 | + member |
| 256 | + for member in get_args(annotation) |
| 257 | + if isinstance(member, type) and is_dataclass(member) |
| 258 | + ) |
| 259 | + return UnionMembers(members) if len(members) > 1 else None |
| 260 | + if isinstance(annotation, AutoRegisterMeta): |
| 261 | + return RegisteredMembers(annotation) |
| 262 | + if ( |
| 263 | + isinstance(annotation, type) |
| 264 | + and is_dataclass(annotation) |
| 265 | + and inspect.isabstract(annotation) |
| 266 | + ): |
| 267 | + return ConcreteSubclasses(annotation) |
| 268 | + return None |
| 269 | + |
| 270 | + @property |
| 271 | + @abstractmethod |
| 272 | + def name(self) -> str: |
| 273 | + """How error messages refer to the family.""" |
| 274 | + |
| 275 | + @abstractmethod |
| 276 | + def members(self) -> tuple[type, ...]: |
| 277 | + """The classes a value of the field may be.""" |
| 278 | + |
| 279 | + def member_tagged(self, tag: str) -> type: |
| 280 | + """The member a stored tag names.""" |
| 281 | + |
| 282 | + members = self._members_by_tag() |
| 283 | + if tag not in members: |
| 284 | + raise ValueError(f"{tag!r} is not a member of {self.name}; members: {sorted(members)}.") |
| 285 | + return members[tag] |
| 286 | + |
| 287 | + def tag_of(self, member: type) -> str: |
| 288 | + """The tag that names ``member`` in stored data.""" |
| 289 | + |
| 290 | + tags = {known: tag for tag, known in self._members_by_tag().items()} |
| 291 | + if member not in tags: |
| 292 | + raise TypeError( |
| 293 | + f"{member.__qualname__} is not a member of {self.name}; " |
| 294 | + f"members: {sorted(tags.values())}." |
| 295 | + ) |
| 296 | + return tags[member] |
| 297 | + |
| 298 | + def _members_by_tag(self) -> dict[str, type]: |
| 299 | + members: dict[str, type] = {} |
| 300 | + for member in self.members(): |
| 301 | + tag = class_tag(member) |
| 302 | + if members.setdefault(tag, member) is not member: |
| 303 | + raise TypeError( |
| 304 | + f"{self.name} has two members tagged {tag!r}: " |
| 305 | + f"{members[tag].__qualname__} and {member.__qualname__}." |
| 306 | + ) |
| 307 | + return members |
| 308 | + |
| 309 | + |
| 310 | +def class_tag(member: type) -> str: |
| 311 | + """The tag naming ``member``: its registry key if it is registered, else its name.""" |
| 312 | + |
| 313 | + tag = to_jsonable(member) if isinstance(member, AutoRegisterMeta) else member.__name__ |
| 314 | + if not isinstance(tag, str): |
| 315 | + raise TypeError( |
| 316 | + f"{member.__qualname__} has the registry key {tag!r}; a member tag is a string." |
| 317 | + ) |
| 318 | + return tag |
| 319 | + |
| 320 | + |
| 321 | +@dataclass(frozen=True) |
| 322 | +class UnionMembers(MemberFamily): |
| 323 | + """The dataclasses listed in a union; its other arms are stored untagged. |
| 324 | +
|
| 325 | + An arm that is itself a family contributes that family's members. |
| 326 | + """ |
| 327 | + |
| 328 | + listed: tuple[type, ...] |
| 329 | + |
| 330 | + @property |
| 331 | + def name(self) -> str: |
| 332 | + return " | ".join(member.__qualname__ for member in self.listed) |
| 333 | + |
| 334 | + def members(self) -> tuple[type, ...]: |
| 335 | + members: list[type] = [] |
| 336 | + for arm in self.listed: |
| 337 | + family = MemberFamily.declared_by(arm) |
| 338 | + members.extend((arm,) if family is None else family.members()) |
| 339 | + return tuple(members) |
| 340 | + |
| 341 | + |
| 342 | +@dataclass(frozen=True) |
| 343 | +class ConcreteSubclasses(MemberFamily): |
| 344 | + """The concrete subclasses of an abstract dataclass, as loaded when asked.""" |
| 345 | + |
| 346 | + base: type |
| 347 | + |
| 348 | + @property |
| 349 | + def name(self) -> str: |
| 350 | + return self.base.__qualname__ |
| 351 | + |
| 352 | + def members(self) -> tuple[type, ...]: |
| 353 | + found: dict[type, None] = {} |
| 354 | + pending = list(self.base.__subclasses__()) |
| 355 | + while pending: |
| 356 | + subclass = pending.pop(0) |
| 357 | + pending.extend(subclass.__subclasses__()) |
| 358 | + if not inspect.isabstract(subclass): |
| 359 | + found[subclass] = None |
| 360 | + return tuple(found) |
| 361 | + |
| 362 | + |
| 363 | +@dataclass(frozen=True) |
| 364 | +class RegisteredMembers(ConcreteSubclasses): |
| 365 | + """The classes a registered family's registry holds, tagged by registry key. |
| 366 | +
|
| 367 | + A stored tag is read by ``registered_class_from_key``, so a family with its |
| 368 | + own spelling decodes tags the way it decodes ``type[Family]`` fields. |
| 369 | + """ |
| 370 | + |
| 371 | + def members(self) -> tuple[type, ...]: |
| 372 | + return tuple( |
| 373 | + member for member in self.base.__registry__.values() if issubclass(member, self.base) |
| 374 | + ) |
| 375 | + |
| 376 | + def member_tagged(self, tag: str) -> type: |
| 377 | + return registered_class_from_key(self.base, tag) |
| 378 | + |
| 379 | + |
152 | 380 | @dataclass(frozen=True) |
153 | 381 | class RegisteredClassChoices(AnnotationChoices): |
154 | 382 | """A field holding one class of a registered family. |
|
0 commit comments