What is ast.FunctionDef in Python?

Python ast module

The ast module (Abstract Syntax Tree)tree representation of source code allows us to interact with and modify the Python code.

Python comes with abstract syntax grammar that is subject to change with every Python release.

This module helps applications process syntax trees and find out what the current syntax grammar looks like programmatically.

Abstract syntax trees are great tools for program analysis and program transformation systems.

Example of an Abstract Syntax Tree

ast.FunctionDef method

ast.FunctionDef(name, args, body, decorator_list, returns, type_comment) is a class defined in the ast module that expresses a function definition in Python. It expresses the definition in the form of an Abstract Syntax Tree.

When the parse() method of ast is called on a Python source code containing a function definition, it invokes the ast.FunctionDef class. This expresses the function definition to a node in an ast tree data structure.

Parameters

  • name represents the function name.

  • args is an argument that contains the function’s arguments.

  • body is the function body represented by a list of nodes.

  • decorator_list is the list of decorators that are to be applied. Decorators are stored outermost first, i.e., the first decorator in the list is applied last.

  • returns is the return annotation.

  • type_comment is an optional string that represents the type annotation as a comment.

Free Resources