|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +import sys |
5 | 6 | import types |
6 | 7 | from enum import Enum |
7 | | -from typing import Annotated, Union, get_args, get_origin |
| 8 | +from typing import Annotated, Literal, Union, get_args, get_origin, get_type_hints |
| 9 | + |
| 10 | + |
| 11 | +def resolved_class_annotations(owner: type) -> dict[str, object]: |
| 12 | + """Resolve nested type strings in the class that declared each field. |
| 13 | +
|
| 14 | + Python 3.10 leaves strings inside PEP 585 aliases unresolved. Complete |
| 15 | + those declarations without interpreting Literal values or Annotated metadata. |
| 16 | + """ |
| 17 | + annotations = get_type_hints(owner, include_extras=True) |
| 18 | + unresolved = set(annotations) |
| 19 | + for declaration in owner.__mro__: |
| 20 | + class_namespace = dict(vars(declaration)) |
| 21 | + module = sys.modules.get(declaration.__module__) |
| 22 | + module_namespace = {} if module is None else vars(module) |
| 23 | + for name in class_namespace.get("__annotations__", {}): |
| 24 | + if name in unresolved: |
| 25 | + annotations[name] = _resolve_nested_type_strings( |
| 26 | + annotations[name], class_namespace, module_namespace |
| 27 | + ) |
| 28 | + unresolved.remove(name) |
| 29 | + return annotations |
| 30 | + |
| 31 | + |
| 32 | +def _resolve_nested_type_strings(annotation: object, globalns: dict, localns: dict) -> object: |
| 33 | + if isinstance(annotation, str): |
| 34 | + return _resolve_nested_type_strings(eval(annotation, globalns, localns), globalns, localns) |
| 35 | + if isinstance(annotation, list): |
| 36 | + resolved = [_resolve_nested_type_strings(member, globalns, localns) for member in annotation] |
| 37 | + return annotation if all(a is b for a, b in zip(resolved, annotation)) else resolved |
| 38 | + origin = get_origin(annotation) |
| 39 | + members = get_args(annotation) |
| 40 | + if not members or origin is Literal: |
| 41 | + return annotation |
| 42 | + if origin is Annotated: |
| 43 | + base = _resolve_nested_type_strings(members[0], globalns, localns) |
| 44 | + return annotation if base is members[0] else Annotated[(base, *members[1:])] |
| 45 | + resolved = tuple(_resolve_nested_type_strings(member, globalns, localns) for member in members) |
| 46 | + if all(member is original for member, original in zip(resolved, members)): |
| 47 | + return annotation |
| 48 | + if isinstance(annotation, types.GenericAlias): |
| 49 | + return types.GenericAlias(origin, resolved) |
| 50 | + if is_union_type(annotation): |
| 51 | + return Union[resolved] # noqa: UP007 - dynamically derived member tuple |
| 52 | + return origin[resolved] |
8 | 53 |
|
9 | 54 |
|
10 | 55 | def is_union_type(annotation: object) -> bool: |
|
0 commit comments