all Python 3astterm
ast.ClassDef
functions and classes
The node of a class definition: the name, base classes, keyword arguments (metaclass=…), the body, decorators and, since 3.12, type parameters.
Syntax
ast.ClassDef(name, bases, keywords, body, decorator_list, type_params)
metaclass=M is not in bases but in keywords — like a keyword argument of a call. name is a string, decorators are a separate decorator_list, and since 3.8 the node's lineno points at the class line, not at the first decorator. The field set grew in 3.12 (type_params), so code that compares _fields or unpacks them positionally breaks between versions.
Examples
import ast
src = '@register\nclass Model(Base, metaclass=Meta):\n pass'
node = ast.parse(src).body[0]
print(node.name, [b.id for b in node.bases]) # → Model ['Base']
print([k.arg for k in node.keywords], node.lineno) # → ['metaclass'] 2
print([d.id for d in node.decorator_list]) # → ['register']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy