Skip to content

Commit ba9c322

Browse files
trissimclaude
andcommitted
0.3.0: a field that admits several classes stores its value under a member tag
A dataclass field whose declared type is a union of dataclasses, an abstract dataclass or a registered class is written as {tag: fields} and read back by the tag. The tag is the member's registry key when it is registered, otherwise its class name. Before, a union member was guessed from the fields present: two members with the same fields were ambiguous and the stored value did not say which class it was. An unknown tag is an error naming the known members. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a88fe56 commit ba9c322

7 files changed

Lines changed: 467 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
0.2.2 is the first 0.2.x release published to PyPI. The 0.2.0 and 0.2.1 tags exist in git, but their publish runs were cancelled, so upgrading from PyPI goes straight from 0.1.16 to 0.2.2. The notes below cover every change in that jump.
44

5+
## 0.3.0
6+
7+
Changed (the stored form of some fields changes; there is no reader for the old form):
8+
- A dataclass field whose declared type admits several classes is stored as `{tag: fields}`, and `dataclass_from_mapping` reads the class from the tag. Before, the member of a union was guessed from which fields were present: two members with the same fields could not be told apart and the stored value did not say which class it was. Three declarations form such a family (`MemberFamily.declared_by`): a union with two or more dataclass members (other arms such as `None` or `str` stay untagged), an abstract dataclass (its concrete subclasses are the members), and a class whose metaclass is `AutoRegisterMeta`. The tag is the member's registry key when it is registered, so it survives a module move or a rename; otherwise it is the class name. The rule holds inside `tuple`, `list`, `Sequence`, `Mapping`, optional and `Annotated` declarations.
9+
- An unknown tag is a `ValueError` naming the known members. A value whose class is not a member of the declared family is a `TypeError` when encoding. Two members with the same tag are a `TypeError`.
10+
- `to_jsonable` reads the declared field types of every dataclass it encodes, so those annotations must resolve at run time (a name imported only under `TYPE_CHECKING` no longer encodes).
11+
512
## 0.2.8
613

714
Added:

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "python-introspect"
7-
version = "0.2.8"
7+
version = "0.3.0"
88
description = "Pure Python introspection toolkit for function signatures, dataclasses, and type hints"
99
readme = "README.md"
1010
requires-python = ">=3.10"

‎src/python_introspect/__init__.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
type resolution for framework-specific types (lazy configs, proxies, etc.)
1010
"""
1111

12-
__version__ = "0.2.8"
12+
__version__ = "0.3.0"
1313

1414
from .signature_analyzer import (
1515
SignatureAnalyzer,
@@ -57,6 +57,7 @@
5757
JsonScalar,
5858
JsonValue,
5959
RegisteredClassChoices,
60+
MemberFamily,
6061
registered_class_from_key,
6162
to_jsonable,
6263
)
@@ -135,6 +136,7 @@
135136
"JsonObject",
136137
"JsonScalar",
137138
"JsonValue",
139+
"MemberFamily",
138140
"registered_class_from_key",
139141
"to_jsonable",
140142
# Module public surfaces

‎src/python_introspect/dataclass_projection.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from metaclass_registry import AutoRegisterMeta
1919

2020
from .annotation_types import is_union_type, resolved_class_annotations
21-
from .jsonable import registered_class_from_key
21+
from .jsonable import MemberFamily, registered_class_from_key
2222
from .validation import validate_annotated_dataclass, validate_annotation_value
2323

2424
DataclassT = TypeVar("DataclassT")
@@ -157,10 +157,32 @@ def _mapping_value_for_annotation(
157157
if not isinstance(value, (list, tuple)):
158158
raise TypeError(f"{path} must be an array.")
159159
return tuple(value)
160+
family = MemberFamily.declared_by(annotation)
161+
if family is not None and isinstance(value, Mapping):
162+
if len(value) != 1:
163+
raise ValueError(
164+
f"{path} must be one member of {family.name} stored as "
165+
f"{{tag: fields}}; got the keys {sorted(map(str, value))}."
166+
)
167+
((tag, member_fields),) = value.items()
168+
try:
169+
member = family.member_tagged(tag)
170+
except ValueError as error:
171+
raise ValueError(f"{path}: {error}") from error
172+
if not isinstance(member_fields, Mapping):
173+
raise TypeError(f"{path}.{tag} must be an object.")
174+
return dataclass_from_mapping(member, member_fields)
160175
if is_union_type(annotation):
161176
successes: list[object] = []
162177
errors: list[Exception] = []
163-
for member_type in get_args(annotation):
178+
untagged_arms = tuple(
179+
arm
180+
for arm in get_args(annotation)
181+
if family is None or not (isinstance(arm, type) and is_dataclass(arm))
182+
)
183+
if family is not None and isinstance(value, family.members()):
184+
return value
185+
for member_type in untagged_arms:
164186
try:
165187
converted = _mapping_value_for_annotation(
166188
member_type,

‎src/python_introspect/jsonable.py‎

Lines changed: 233 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,29 @@
1010
annotated ``type[Family]``. A family whose boundary spelling is not its
1111
registry (for example one resolved through an active subset) registers its own
1212
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.
1319
"""
1420

1521
from __future__ import annotations
1622

1723
import inspect
18-
from collections.abc import Callable, Mapping
24+
from abc import ABC, abstractmethod
25+
from collections.abc import Callable, Mapping, Sequence, Set
1926
from dataclasses import dataclass, fields, is_dataclass
2027
from enum import Enum
2128
from functools import singledispatch
2229
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
2432

2533
from metaclass_registry import AutoRegisterMeta
2634

35+
from .annotation_types import is_union_type, resolved_class_annotations
2736
from .choices import AnnotationChoices
2837
from .signature_analyzer import signature_analysis_target
2938

@@ -40,15 +49,94 @@
4049
JsonObject: TypeAlias = Mapping[str, JsonValue]
4150

4251

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+
4368
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."""
4570

71+
declared_types = _declared_field_types(type(value))
4672
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+
)
4876
for declared_field in fields(value)
4977
}
5078

5179

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+
52140
@singledispatch
53141
def to_jsonable(value: object) -> JsonValue:
54142
"""Project dataclasses and registered values into JSON-native data."""
@@ -100,7 +188,7 @@ def _jsonable_registered_type(value: AutoRegisterMeta) -> JsonValue:
100188
)
101189
if declaring_owner is None:
102190
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."
104192
)
105193
key = vars(declaring_owner)[key_attribute]
106194
if key is None:
@@ -149,6 +237,146 @@ def _registered_class_from_registry(family: AutoRegisterMeta, key: JsonValue) ->
149237
return matches[0]
150238

151239

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+
152380
@dataclass(frozen=True)
153381
class RegisteredClassChoices(AnnotationChoices):
154382
"""A field holding one class of a registered family.

‎tests/test_dataclass_projection.py‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -244,23 +244,6 @@ class NumericValue:
244244
assert type(dataclass_from_mapping(NumericValue, {"value": 1}).value) is int
245245

246246

247-
def test_dataclass_mapping_rejects_ambiguous_structured_unions() -> None:
248-
@dataclass(frozen=True)
249-
class Left:
250-
value: int
251-
252-
@dataclass(frozen=True)
253-
class Right:
254-
value: int
255-
256-
@dataclass(frozen=True)
257-
class Envelope:
258-
payload: Left | Right
259-
260-
with pytest.raises(TypeError, match="ambiguously matches multiple members"):
261-
dataclass_from_mapping(Envelope, {"payload": {"value": 1}})
262-
263-
264247
@dataclass(frozen=True)
265248
class AnnotatedSequenceEnvelope:
266249
nodes: Annotated[Sequence["RecursiveSequenceNode"], "display text"]

0 commit comments

Comments
 (0)