From 021039a4c3b2219e1bad47db1875777dfbde7c61 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Wed, 18 Nov 2026 02:50:39 -0500 Subject: [PATCH] resolved_class_annotations: resolved once per class and kept A class's resolved annotations are a fact about the class. Every validated dataclass instance asks for them (AnnotatedDataclassValidationMixin), and resolving them again for each instance (get_type_hints, compiling each forward reference) was most of building a nested settings object: in Toad's Qt client at a phone's speed, 0.54 s of a sidebar drag's 0.70 s of settings writes, and about half of opening a view's configuration. resolved_class_annotations keeps the answer per class (a WeakKeyDictionary, read-only), and jsonable's own per-class copy of it goes. A class whose annotations do not resolve yet raises and keeps nothing, so a later call resolves it then. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RnH6dT7wdh7i4tjJZQdFu3 --- src/python_introspect/annotation_types.py | 21 +++++++++++- src/python_introspect/jsonable.py | 23 +++++-------- tests/test_class_annotation_cache.py | 40 +++++++++++++++++++++++ 3 files changed, 69 insertions(+), 15 deletions(-) create mode 100644 tests/test_class_annotation_cache.py diff --git a/src/python_introspect/annotation_types.py b/src/python_introspect/annotation_types.py index 9af4c01..7466bed 100644 --- a/src/python_introspect/annotation_types.py +++ b/src/python_introspect/annotation_types.py @@ -4,7 +4,10 @@ import sys import types +from collections.abc import Mapping from enum import Enum +from types import MappingProxyType +from weakref import WeakKeyDictionary from typing import ( Annotated, ForwardRef, @@ -16,7 +19,10 @@ ) -def resolved_class_annotations(owner: type) -> dict[str, object]: +_RESOLVED_BY_CLASS: WeakKeyDictionary[type, Mapping[str, object]] = WeakKeyDictionary() + + +def resolved_class_annotations(owner: type) -> Mapping[str, object]: """Resolve nested type strings in the class that declared each field. Python 3.10 leaves strings inside PEP 585 aliases unresolved. Complete @@ -24,7 +30,20 @@ def resolved_class_annotations(owner: type) -> dict[str, object]: A recursive alias such as ``V = int | list["V"]`` names itself; the inner reference is left as a ``ForwardRef``, the form ``get_type_hints`` produces for it on Python 3.11 and later. + + The answer is a fact about the class, so it is resolved once per class and kept + (read-only) while the class lives. Every validated instance asks for its class's + annotations (``AnnotatedDataclassValidationMixin``), and resolving them again for + each one was most of building a nested settings object. A class whose annotations + do not resolve yet raises, and nothing is kept, so a later call resolves it then. """ + resolved = _RESOLVED_BY_CLASS.get(owner) + if resolved is None: + resolved = _RESOLVED_BY_CLASS[owner] = MappingProxyType(_resolve_class_annotations(owner)) + return resolved + + +def _resolve_class_annotations(owner: type) -> dict[str, object]: annotations = get_type_hints( owner, localns={owner.__name__: owner}, include_extras=True ) diff --git a/src/python_introspect/jsonable.py b/src/python_introspect/jsonable.py index 4daee51..42b419d 100644 --- a/src/python_introspect/jsonable.py +++ b/src/python_introspect/jsonable.py @@ -28,7 +28,6 @@ from functools import singledispatch from pathlib import Path from typing import Annotated, ForwardRef, TypeAlias, get_args, get_origin -from weakref import WeakKeyDictionary from metaclass_registry import AutoRegisterMeta @@ -49,20 +48,16 @@ JsonObject: TypeAlias = Mapping[str, JsonValue] -_FIELD_TYPES_BY_DATACLASS: WeakKeyDictionary[type, Mapping[str, object]] = WeakKeyDictionary() - - def _declared_field_types(owner: type) -> Mapping[str, object]: - if owner not in _FIELD_TYPES_BY_DATACLASS: - try: - _FIELD_TYPES_BY_DATACLASS[owner] = resolved_class_annotations(owner) - except NameError as error: - raise TypeError( - f"{owner.__qualname__} cannot be projected: a field type does not resolve " - f"at run time ({error}). A field's declared type decides its stored form, " - "so import the name outside TYPE_CHECKING." - ) from error - return _FIELD_TYPES_BY_DATACLASS[owner] + """The owner's resolved field types, kept per class by `resolved_class_annotations`.""" + try: + return resolved_class_annotations(owner) + except NameError as error: + raise TypeError( + f"{owner.__qualname__} cannot be projected: a field type does not resolve " + f"at run time ({error}). A field's declared type decides its stored form, " + "so import the name outside TYPE_CHECKING." + ) from error def _jsonable_dataclass(value: object) -> JsonValue: diff --git a/tests/test_class_annotation_cache.py b/tests/test_class_annotation_cache.py new file mode 100644 index 0000000..ca60d9b --- /dev/null +++ b/tests/test_class_annotation_cache.py @@ -0,0 +1,40 @@ +"""A class's resolved annotations are a fact about the class: resolved once, kept read-only.""" + +from dataclasses import dataclass + +import pytest + +from python_introspect.annotation_types import resolved_class_annotations + + +def test_class_annotations_resolve_once_per_class_and_read_only() -> None: + """Every validated instance asks for its class's annotations: they are resolved once + and kept for the class, read-only.""" + + @dataclass + class Declared: + count: int + names: list[str] + + first = resolved_class_annotations(Declared) + assert first == {"count": int, "names": list[str]} + assert resolved_class_annotations(Declared) is first + with pytest.raises(TypeError): + first["count"] = str # type: ignore[index] + + +def test_a_class_that_does_not_resolve_yet_is_resolved_on_a_later_call() -> None: + """Nothing is kept for a class whose annotations do not resolve, so a call once the + name exists resolves it.""" + + @dataclass + class Later: + value: "NotYetDefined" # noqa: F821 + + with pytest.raises(NameError): + resolved_class_annotations(Later) + globals()["NotYetDefined"] = float + try: + assert resolved_class_annotations(Later) == {"value": float} + finally: + del globals()["NotYetDefined"]