Python Glossary Русский

Python 3.0+astterm

ast.Nonlocal

functions and classes

Node for the nonlocal statement: names is a list of names as strings.

Syntax

ast.Nonlocal(names)

The names list holds plain strings, not Name nodes, so ast.walk filtered on Name never finds them. ast.parse checks syntax only: nonlocal at module level yields a perfectly valid tree, and the "not allowed at module level" error appears only in compile(). The same holds for return and yield outside a function.

Examples

import ast
tree = ast.parse('nonlocal a, b')
print(type(tree.body[0]).__name__, tree.body[0].names)  # → Nonlocal ['a', 'b']
try:
    compile(tree, '<ast>', 'exec')
except SyntaxError as e:
    print(e.msg)  # → nonlocal declaration not allowed at module level

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy