all Python 3astterm
ast.FunctionDef
functions and classes
The node for a def statement: name, args (an arguments node), body, decorator_list, returns, type_comment and, since 3.12, type_params.
Syntax
ast.FunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)
async def is a different class, AsyncFunctionDef, and isinstance(node, ast.FunctionDef) misses it: check a tuple of both. lineno points at the def line, not the first decorator. The docstring is just the first Expr with a Constant in body; ast.get_docstring extracts it. The return annotation sits in returns as an expression node, not a string.
Examples
import ast
src = '@cache\ndef area(r: float) -> float:\n "Площадь."\n return 3.14 * r * r'
fn = ast.parse(src).body[0]
print(type(fn).__name__, fn.name, fn.lineno) # → FunctionDef area 2
print(fn.decorator_list[0].id, fn.returns.id, fn.args.args[0].arg) # → cache float r
print(ast.get_docstring(fn)) # → Площадь.
import ast
tree = ast.parse('def f(): pass\nasync def g(): pass')
print([n.name for n in tree.body if isinstance(n, ast.FunctionDef)]) # → ['f']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy