Python Glossary Русский

Python 3.14+annotationlibterm

annotationlib.Format

annotation formats

An enum of the formats lazy annotations can be retrieved in: VALUE (evaluate), FORWARDREF (substitute placeholders), STRING (source text).

Syntax

annotationlib.Format.VALUE | Format.FORWARDREF | Format.STRING

The main Python 3.14 trap: annotations are no longer evaluated at def time, so a forward reference to a class not yet defined does not fail at definition, it raises NameError on the first read in VALUE format (which is what __annotations__ and get_annotations use by default). FORWARDREF never fails: known names become real objects, unknown ones become ForwardRef. STRING evaluates nothing and returns the source text, so you cannot compare its types with int. VALUE_WITH_FAKE_GLOBALS is an internal format for __annotate__ functions, and get_annotations rejects it with ValueError.

Examples

# Python 3.14+
from annotationlib import get_annotations, Format
def move(p: Point) -> None: ...  # Point ещё не объявлен — и это не ошибка
try:
    get_annotations(move)  # формат VALUE по умолчанию
except NameError as e:
    print(e)  # → name 'Point' is not defined
print(get_annotations(move, format=Format.STRING))  # → {'p': 'Point', 'return': 'None'}
ref = get_annotations(move, format=Format.FORWARDREF)['p']
print(type(ref).__name__, ref.__forward_arg__)  # → ForwardRef Point
class Point: ...
print(get_annotations(move))  # → {'p': <class '__main__.Point'>, 'return': None}
# Python 3.14+
from annotationlib import Format
print([f.name for f in Format])  # → ['VALUE', 'VALUE_WITH_FAKE_GLOBALS', 'FORWARDREF', 'STRING']
print(int(Format.VALUE), int(Format.STRING))  # → 1 4

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy