What is ast.YieldFrom(value) in Python?

Abstract Syntax Tree

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.

Code

import ast
from pprint import pprint
class 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)

Explanation

  • We define a 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.
  • We initialize a visitor object of the class YieldFromVisitor.
  • We write Python code that contains a 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.
  • The ast.dump() method returns a formatted string of the tree structure in tree.
  • The visit method available to the visitor object visits all the nodes in the tree structure.

Free Resources