Trusted answers to developer questions

What is ast.ClassDef in Python?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Readers should have a general knowledge of Python.

Python ast module

The ast module in Python generates an Abstract Syntax Tree which is a tree representation of Python source code.

Python comes with an abstract syntax grammar, which is subject to change with every Python release. This module helps applications process trees of syntax and find out programmatically what the current syntax grammar looks like.

Abstract Syntax Trees are great tools for program analysis and program transformation systems.

ast.ClassDef

ast.ClassDef is a class defined in the ast module that expresses the class definition in Python in the form of an Abstract Syntax Tree. When the parse() method of ast is called on a Python source code that contains a class definition, the ast.ClassDef class is invoked, which expresses the class definition to a node in an ast tree data structure. The ast.ClassDef class represents the ClassDef node type in the ast tree.

Class parameters

  • name: A raw string containing the name of the class.
  • bases: A list of specified parent classes in the arguments of class definition.
  • keywords: A list of keyword nodes, primarily used for metaclass.
  • starargs: A single node, similar to a function call. Arguments in this parameter are expanded to the list of base classes.
  • kwargs: A single node, similar to a function call. Arguments in this parameter are passed to the metaclass.
  • body: A list of nodes representing the body code of the class.
  • decorators: A list of name nodes, similar to the function definition.

Example

import ast
from pprint import pprint
class ClassDefVisitor(ast.NodeVisitor):
def visit_ClassDef(self, node):
print('Node type: ClassDef\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)
def visit_Name(self, node):
print('Node type: Name\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
def visit_Pass(self, node):
print('Node type: Pass\nFields:', node._fields)
ast.NodeVisitor.generic_visit(self, node)
visitor = ClassDefVisitor()
tree = ast.parse("""
@decorator1
@decorator2
class Student(Person, metaclass=meta):
pass
""")
pprint(ast.dump(tree))
visitor.visit(tree)

Explanation

  • We define a ClassDefVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_ClassDef, visit_keyword, visit_Name, and visit_Pass methods in the parent class, which receive the ClassDef, keyword, Name, and Pass 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 ClassDefVisitor.

  • We write python code where the Student class is defined that extends from the parent class Person. We pass this class definition to the ast.parse() method, which returns the result of the expression after evaluation, and stores the result in the tree.

  • One of the nodes of the tree structure will contain the node ClassDef, and information about the class definition will be stored in the fields of the node.

  • 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. As you can observe the output of the program, the nodes ClassDef, Name, keyword, and Pass are visited.

RELATED TAGS

python
abstractsyntaxtree
Did you find this helpful?