Python Glossary Русский

all Python 3astterm

ast.GeneratorExp

expressions

The node for a generator expression (x for x in y): elt is the computed expression, generators is a list of comprehension nodes.

Syntax

ast.GeneratorExp(elt, generators)

The generator's own parentheses are invisible in the tree: in sum(x for x in y) the GeneratorExp sits right in Call.args, and the tree cannot tell it from sum((x for x in y)). Several for clauses become several comprehension nodes in generators, left to right; if filters live in comprehension.ifs, not in GeneratorExp.

Examples

import ast
call = ast.parse('sum(x * x for x in data if x)', mode='eval').body
gen = call.args[0]
print(type(gen).__name__, type(gen.elt).__name__)  # → GeneratorExp BinOp
print(gen.generators[0].target.id, len(gen.generators[0].ifs))  # → x 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy