ast.YieldFrom
is a class defined in the ast
module that expresses the yield from
statement in Python in the form of an Abstract Syntax Tree. When the parse()
method of ast
is called on Python source code that contains a yield from
statement, the ast.Lambda
class is invoked, which expresses the YieldFrom
statement to a node in an ast
tree data structure.
The ast.YieldFrom
class represents the Lambda node type in the ast
tree. The class parameter value
is the ast
node representing the value after the from
keyword.
import astfrom pprint import pprintclass YieldFromVisitor(ast.NodeVisitor):def visit_YieldFrom(self, node):print('Node type: YieldFrom\nFields:', node._fields)ast.NodeVisitor.generic_visit(self, node)def visit_Name(self, node):print('Node type: Name\nFields:', node._fields)ast.NodeVisitor.generic_visit(self, node)visitor = YieldFromVisitor()tree = ast.parse("yield from x")pprint(ast.dump(tree))visitor.visit(tree)
YieldFrom
class that extends from the parent class ast.NodeVisitor
. We override the predefined visit_YieldFrom
, and visit_Name
methods in the parent class, which receive the YieldFrom
, and Name
nodes, respectively. In the method, we print the type and the fields inside the node and call the generic_visit()
method, which invokes the propagation of visit on the children nodes of the input node.YieldFromVisitor
.yield from
statement. We pass the code to the ast.parse()
method, which returns the result of the expression after evaluation, and store the result in tree.ast.dump()
method returns a formatted string of the tree structure in tree.visit
method available to the visitor object visits all the nodes in the tree structure.