Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/python_introspect/annotation_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -16,15 +19,31 @@
)


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
those declarations without interpreting Literal values or Annotated metadata.
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
)
Expand Down
23 changes: 9 additions & 14 deletions src/python_introspect/jsonable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down
40 changes: 40 additions & 0 deletions tests/test_class_annotation_cache.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading