Skip to main content

get_function_as_str

get_function_as_str(
    func_or_method: Callable,
) ‑> str
Extract the body of a function or method’s source code, excluding its name, docstrings, and comments. Parameters:
NameTypeDefaultDescription
func_or_methodtp.Callable--The function from which to extract the source code body.
Returns:
TypeDescription
strThe source code of the function body, with function name, docstrings, and comments removed. Each line is stripped of leading/trailing whitespace, and empty lines are excluded.
Raises:
TypeDescription
OSErrorIf the source code of the function cannot be retrieved (e.g., for built-in functions).
SyntaxErrorIf the function’s source code cannot be parsed into an AST.
Examples: python
>>> def example_function(x):
...     '''This is a docstring.'''
...     y = x + 1  # Add 1 to x
...     print(y)   # Print the result
...     return y   # Return the result
...
>>> print(get_function_body(example_function))
y = x + 1
print(y)
return y