What is ast.Call(func,args,keywords,starargs,kwargs) in Python?

Abstract Syntax Tree

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 Abstract Syntax Treetree representation of source code. When the 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 like func(*starargs).
  • kwargs: an optional parameter representing Python syntax of a function that can be called with a variable number of keyword arguments like func(**kwargs).

Example

import ast
from pprint import pprint
class 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 CallVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_Call, visit_keyword, visit_Constant, and visit_Name methods in the parent class, which receive the Call, keyword, Constant, 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 CallVisitor.
  • We write a Python function call of myfunc(a, 100, found=True) and send it to the ast.parse() method with mode='eval', which returns the result of the expression after evaluation and stores it in tree.
  • The ast.dump() method returns a formatted string of the tree structure in tree.
  • The visit method available to the visitor objects visits all the nodes in the tree structure.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved