Python Glossary Русский

all Python 3astterm

ast.comprehension

expressions

The node for one for ... in ... [if ...] clause inside a list, set or dict comprehension or a generator expression. Fields: target, iter, ifs, is_async.

Syntax

ast.comprehension(target, iter, ifs, is_async)

Several for clauses in one expression are several comprehension nodes in the generators list, left to right, and all ifs following a for are collected in its ifs. is_async is an int 0 or 1, not a bool. A comprehension has no lineno positions; take them from the parent ListComp/GeneratorExp.

Examples

import ast
comp = ast.parse('[x * y for x in a if x for y in b if y if y > x]', mode='eval').body
for g in comp.generators:
    print(ast.unparse(g.target), ast.unparse(g.iter), len(g.ifs), g.is_async)
# → x a 1 0 / y b 2 0
print(hasattr(comp.generators[0], 'lineno'))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy