Python Glossary Русский

all Python 3astterm

ast.Assert

statements

The node of an assert statement: the tested expression in test and an optional message in msg.

Syntax

ast.Assert(test, msg=None)

Wrapping both parts in parentheses — assert (x, 'text') — makes test a Tuple, which is always true; in the tree it shows up as a test of type Tuple, which is exactly how this bug is caught. Without a message msg is None. Under python -O the compiler drops the whole node, so assert must not validate user input.

Examples

import ast
node = ast.parse('assert x > 0, "negative"').body[0]
print(type(node.test).__name__, node.msg.value)  # → Compare negative
bad = ast.parse('assert (x, "negative")').body[0]
print(type(bad.test).__name__, bad.msg)  # → Tuple None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy