Python Glossary Русский

all Python 3astterm

ast.stmt

root and base nodes

The abstract base class of all statements: assignments, if, for, def, import, return and others. Items of body lists are always stmt.

Syntax

isinstance(node, ast.stmt)

The main trap is the Expr node: a call f(x) on its own line is an Expr statement (a stmt subclass), and the call itself sits in its value field and is an expr. Every stmt has lineno, col_offset, end_lineno, end_col_offset; isinstance(n, ast.stmt) conveniently picks out the program's statements during a walk.

Examples

import ast
tree = ast.parse('x = 1\nprint(x)')
print([type(s).__name__ for s in tree.body])  # → ['Assign', 'Expr']
print(all(isinstance(s, ast.stmt) for s in tree.body))  # → True
print(isinstance(tree.body[1].value, ast.stmt))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy