Python Glossary Русский

Python 3.10+inspectfunction

inspect.get_annotations()

signatures

Safely returns the annotations dict of a function, class or module; it can evaluate string annotations with eval_str=True.

Syntax

inspect.get_annotations(obj, *, globals=None, locals=None, eval_str=False)

It always returns a fresh dict, and an empty {} where there are no annotations, while __annotations__ behaves differently across objects. String annotations (quoted, or under from __future__ import annotations) stay strings by default; eval_str=True evaluates them and may raise NameError for an undefined name. Since 3.14 it is annotationlib.get_annotations and annotations are evaluated lazily. Unlike typing.get_type_hints, which merges a class's bases, this one returns only the object's own annotations.

Examples

import inspect
def f(a: 'int', b: float = 1.0) -> 'str': pass
print(inspect.get_annotations(f))
# → {'a': 'int', 'b': <class 'float'>, 'return': 'str'}
print(inspect.get_annotations(f, eval_str=True))
# → {'a': <class 'int'>, 'b': <class 'float'>, 'return': <class 'str'>}
import inspect, typing
class A:
    x: int
class B(A):
    y: str
print(inspect.get_annotations(B))  # → {'y': <class 'str'>}
print(typing.get_type_hints(B))  # → {'x': <class 'int'>, 'y': <class 'str'>}
print(inspect.get_annotations(len))  # → {}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy