PyDocs

Nav

Python Runtime Services

get_annotations

inspect

function · Added in 3.10 (source)
  • get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=annotationlib.Format.VALUE)
Compute the annotations dict for an object.

obj may be a callable, class, module, or other object with
__annotate__ or __annotations__ attributes.
Passing any other object raises TypeError.

The *format* parameter controls the format in which annotations are returned,
and must be a member of the Format enum or its integer equivalent.
For the VALUE format, the __annotations__ is tried first; if it
does not exist, the __annotate__ function is called. The
FORWARDREF format uses __annotations__ if it exists and can be
evaluated, and otherwise falls back to calling the __annotate__ function.
The STRING format tries __annotate__ first, and falls back to
using __annotations__, stringified using annotations_to_string().

This function handles several details for you:

  * If eval_str is true, values of type str will
    be un-stringized using eval().  This is intended
    for use with stringized annotations
    ("from __future__ import annotations").
  * If obj doesn't have an annotations dict, returns an
    empty dict.  (Functions and methods always have an
    annotations dict; classes, modules, and other types of
    callables may not.)
  * Ignores inherited annotations on classes.  If a class
    doesn't have its own annotations dict, returns an empty dict.
  * All accesses to object members and dict values are done
    using getattr() and dict.get() for safety.
  * Always, always, always returns a freshly-created dict.

eval_str controls whether or not values of type str are replaced
with the result of calling eval() on those values:

  * If eval_str is true, eval() is called on values of type str.
  * If eval_str is false (the default), values of type str are unchanged.

globals and locals are passed in to eval(); see the documentation
for eval() for more information.  If either globals or locals is
None, this function may replace that value with a context-specific
default, contingent on type(obj):

  * If obj is a module, globals defaults to obj.__dict__.
  * If obj is a class, globals defaults to
    sys.modules[obj.__module__].__dict__ and locals
    defaults to the obj class namespace.
  * If obj is a callable, globals defaults to obj.__globals__,
    although if obj is a wrapped function (using
    functools.update_wrapper()) it is first unwrapped.
Changed in 3.14
  • 3.14: This function is now an alias for annotationlib.get_annotations(). Calling it as inspect.get_annotations will continue to work.
0 Examples
No examples for inspect/get_annotations.
See Also
No see-alsos for inspect/get_annotations
0 Notes
No notes for get_annotations