Python Glossary Русский

all Python 3astfunction

ast.get_docstring()

helper functions

Returns the docstring of a module, function or class from an AST, without importing or running the code. Handy for checking that functions are documented.

Syntax

ast.get_docstring(node, clean=True)

A docstring is only a string that is the first statement of the body; a string after another statement gives None. The node must be a Module, FunctionDef, AsyncFunctionDef or ClassDef; any other node raises TypeError. By default clean=True strips the common indentation (like inspect.cleandoc); clean=False returns the raw text.

Examples

import ast
src = 'def area(r):\n    """Площадь круга."""\n    return 3.14 * r * r\n\ndef bare():\n    pass'
tree = ast.parse(src)
for f in tree.body:
    print(f.name, ast.get_docstring(f))  # → area Площадь круга. / bare None
import ast
tree = ast.parse('x = 1\n"""не докстринг"""')
print(ast.get_docstring(tree))  # → None

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy