What is ast.Call(func,args,keywords,starargs,kwargs) in Python?
ast.Call(func, args, keywords, starargs, kwargs) is a class in Python defined in the ast module that is used to express a function call in the form of an parse() method of ast is called on a Python source code that contains a function call, the ast.Call class is invoked. It expresses the function call to a node in an ast tree data structure. The ast.Call class represents the Call node type in the ast tree.
Class parameters:
func: a node containing the name of the function. It can be of type Name or Attribute.args: a list of argument nodes passed by position.keywords: a list of arguments passed by keywords, represented by keyword objects.starargs: an optional parameter representing Python syntax of a function that can be called with a variable number of arguments likefunc(*starargs).kwargs: an optional parameter representing Python syntax of a function that can be called with a variable number of keyword arguments likefunc(**kwargs).
Example
import astfrom pprint import pprintclass CallVisitor(ast.NodeVisitor):def visit_Call(self,node):print('Node type: Call\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_Constant(self,node):print('Node type: Constant\nFields: ', node._fields)ast.NodeVisitor.generic_visit(self, node)def visit_keyword(self,node):print('Node type: keyword\nFields: ', node._fields)ast.NodeVisitor.generic_visit(self, node)visitor = CallVisitor()tree = ast.parse("myfunc(a, 100, found=True)", mode='eval')pprint(ast.dump(tree))visitor.visit(tree)
Explanation
- We define a
CallVisitorclass that extends from the parent classast.NodeVisitor. We override the predefinedvisit_Call,visit_keyword,visit_Constant, andvisit_Namemethods in the parent class, which receive theCall,keyword,Constant, andNamenodes, respectively. In the method, we print the type and the fields inside the node and call thegeneric_visit()method, which invokes the propagation of visit on the children nodes of the input node. - We initialize a
visitorobject of the classCallVisitor. - We write a Python function call of
myfunc(a, 100, found=True)and send it to theast.parse()method withmode='eval', which returns the result of the expression after evaluation and stores it intree. - The
ast.dump()method returns a formatted string of the tree structure intree. - The
visitmethod available to thevisitorobjects visits all the nodes in the tree structure.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved