What is ast.Lambda(args, body) in Python?

Abstract Syntax Tree

ast.Lambda is a class defined in the ast module that expresses the lambda 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 lambda statement, the ast.Lambda class is invoked, which expresses the lambda statement to a node in an ast tree data structure. The ast.Lambda class represents the Lambda node type in the ast tree. The class parameter args is a list of ast nodes representing the arguments to the lambda function, and the body parameter represents the ast node in the body of the lambda block.

Code

import ast
from pprint import pprint
class LambdaVisitor(ast.NodeVisitor):
def visit_Lambda(self, node):
print('Node type: Lambda\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)
def visit_BinOp(self, node):
print('Node type: BinOp\nFields: ', node._fields)
self.generic_visit(node)
visitor = LambdaVisitor()
tree = ast.parse("lambda a, b : a * b")
pprint(ast.dump(tree))
visitor.visit(tree)

Explanation

  • We define a LambdaVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_Lambda, visit_BinOp, and visit_Name methods in the parent class, which receive the Lambda, BinOp, 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 LambdaVisitor.
  • We write Python code that contains a Lambda statement. We pass the code to the ast.parse() method, which returns the result of the expression after evaluation, and store the result in a tree.
  • The ast.dump() method returns a formatted string of the tree structure in a tree.
  • The visit method available to the visitor object visits all the nodes in the tree structure.