Python 3.8+astterm
ast.NamedExpr
expressions
Node for the walrus operator (x := value): target is a Name with Store, value is the expression.
Syntax
ast.NamedExpr(target, value)
It is an expression, not a statement: (x := 1) at top level parses as an Expr wrapping a NamedExpr, while x := 1 without parentheses is a SyntaxError already in ast.parse. The target can only be a plain name: unlike Assign it never holds an attribute, a subscript or a tuple. Search for assignments in NamedExpr too, or names bound in if (n := len(a)) > 10 slip through.
Examples
import ast
stmt = ast.parse('if (n := len(a)) > 10: pass').body[0]
w = stmt.test.left
print(type(w).__name__, w.target.id, type(w.target.ctx).__name__) # → NamedExpr n Store
import ast
try:
ast.parse('x := 1')
except SyntaxError as e:
print(type(e).__name__) # → SyntaxError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy