Python Glossary Русский

Python 3.5+typingfunction

typing.get_type_hints

introspection

Return a dict of an object's type hints, with forward references resolved.

Syntax

typing.get_type_hints(obj)

Unlike reading obj.__annotations__ directly, it evaluates string annotations into real type objects: under from __future__ import annotations (PEP 563) every annotation is stored as a string, and get_type_hints turns them back into types (annotationlib.get_annotations(obj, eval_str=True) can do this too), resolving forward references in the object's globals (raising NameError if a name isn't reachable). For a class it also merges annotations across the whole inheritance chain, and it drops Annotated metadata by default — pass include_extras=True to keep it.

Examples

from typing import get_type_hints
def f(x: int) -> bool: ...
print(get_type_hints(f)['x'] is int)   # → True
print(get_type_hints(f)['return'] is bool)   # → True
from typing import get_type_hints
def g(x: 'int') -> 'str': ...
print(g.__annotations__['x'])   # → int
print(get_type_hints(g)['x'] is int)   # → True
from typing import get_type_hints
class Point: x: int; y: int
print(sorted(get_type_hints(Point)))   # → ['x', 'y']
from typing import get_type_hints
def h(a, b): ...
print(get_type_hints(h))   # → {}

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy