Python 3.6+astterm
ast.AnnAssign
statements
The node of an annotated assignment x: int = 5: the target, the annotation, an optional value and the simple flag. An annotation without a value is also AnnAssign.
Syntax
ast.AnnAssign(target, annotation, value=None, simple)
In x: int there is no value — value is None, and code reading node.value.value fails with AttributeError. The simple flag is 1 only for a bare name; for self.x: int and for a parenthesised name (x): int it is 0 — such annotations do not go into the module or class __annotations__. There is always one target: unpacking a, b: int is a syntax error.
Examples
import ast
node = ast.parse('x: int = 5').body[0]
print(node.target.id, node.annotation.id, node.value.value, node.simple) # → x int 5 1
bare = ast.parse('self.x: int').body[0]
print(type(bare.target).__name__, bare.value, bare.simple) # → Attribute None 0
See also
Open in the full glossarydocs.python.orgReport an inaccuracy