Get the annotations for a class. This is similar to ``typing.get_type_hints``, except: - We maintain it - It leaves extras like ``Annotated``/``ClassVar`` alone - It resolves any parametrized generics in the class mro. The returned mapping may still include ``TypeVar`` values
(obj)
| 107 | |
| 108 | |
| 109 | def get_class_annotations(obj): |
| 110 | """Get the annotations for a class. |
| 111 | |
| 112 | This is similar to ``typing.get_type_hints``, except: |
| 113 | |
| 114 | - We maintain it |
| 115 | - It leaves extras like ``Annotated``/``ClassVar`` alone |
| 116 | - It resolves any parametrized generics in the class mro. The returned |
| 117 | mapping may still include ``TypeVar`` values, but those should be treated |
| 118 | as their unparametrized variants (i.e. equal to ``Any`` for the common case). |
| 119 | |
| 120 | Note that this function doesn't check that Generic types are being used |
| 121 | properly - invalid uses of `Generic` may slip through without complaint. |
| 122 | |
| 123 | The assumption here is that the user is making use of a static analysis |
| 124 | tool like ``mypy``/``pyright`` already, which would catch misuse of these |
| 125 | APIs. |
| 126 | """ |
| 127 | hints = {} |
| 128 | mro, typevar_mappings = _get_class_mro_and_typevar_mappings(obj) |
| 129 | |
| 130 | for cls in mro: |
| 131 | if cls in (typing.Generic, object): |
| 132 | continue |
| 133 | |
| 134 | mapping = typevar_mappings.get(cls) |
| 135 | cls_locals = dict(vars(cls)) |
| 136 | cls_globals = getattr(sys.modules.get(cls.__module__, None), "__dict__", {}) |
| 137 | |
| 138 | ann = _get_class_annotations(cls) |
| 139 | for name, value in ann.items(): |
| 140 | if name in hints: |
| 141 | continue |
| 142 | if isinstance(value, str): |
| 143 | value = _forward_ref(value) |
| 144 | value = _eval_type(value, cls_locals, cls_globals) |
| 145 | if mapping is not None: |
| 146 | value = _apply_params(value, mapping) |
| 147 | if value is None: |
| 148 | value = type(None) |
| 149 | hints[name] = value |
| 150 | return hints |
| 151 | |
| 152 | |
| 153 | # A mapping from a type annotation (or annotation __origin__) to the concrete |
searching dependent graphs…