Python Glossary Русский

Python 3.14+annotationlibfunction

annotationlib.get_annotate_from_class_namespace()

low-level helpers

Retrieves the __annotate__ function from a class namespace dict while the class is still being created, for example in a metaclass __new__.

Syntax

annotationlib.get_annotate_from_class_namespace(namespace)

Before 3.14 a metaclass read ns['__annotations__'], a ready dict. Since 3.14 that key is absent from the namespace: the compiler stores a function there under an internal name, and old code silently sees no annotations or gets KeyError. This function is the portable way to fetch it; None means the class body has no annotations. Call the result through call_annotate_function, otherwise only VALUE format is available.

Examples

# Python 3.14+
from annotationlib import get_annotate_from_class_namespace, call_annotate_function, Format
seen = {}
class Meta(type):
    def __new__(mcls, name, bases, ns):
        annotate = get_annotate_from_class_namespace(ns)
        seen[name] = annotate and call_annotate_function(annotate, Format.STRING)
        print(name, '__annotations__' in ns)  # → User False / Empty False
        return super().__new__(mcls, name, bases, ns)
class User(metaclass=Meta):
    name: str
    boss: Manager  # ссылка вперёд
class Empty(metaclass=Meta): ...
print(seen)  # → {'User': {'name': 'str', 'boss': 'Manager'}, 'Empty': None}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy