Skip to content

Instantly share code, notes, and snippets.

@noklam
Created February 1, 2024 13:58
Show Gist options
  • Save noklam/d45764cb97b997e8c8d0565e6d914006 to your computer and use it in GitHub Desktop.
Save noklam/d45764cb97b997e8c8d0565e6d914006 to your computer and use it in GitHub Desktop.
Get Python function body without the signatures
def _prepare_function_body(func: Callable) -> str:
# https://stackoverflow.com/questions/38050649/getting-a-python-functions-source-code-without-the-definition-lines
all_source_lines = inspect.getsourcelines(func)[0]
# Remove any decorators
func_lines = dropwhile(lambda x: x.startswith("@"), all_source_lines)
line: str = next(func_lines).strip()
if not line.startswith("def "):
return line.rsplit(",")[0].strip()
# Handle functions that are not one-liners
first_line = next(func_lines)
# Find the indentation of the first line
indentation = len(first_line) - len(first_line.lstrip())
body = "".join(
[first_line[indentation:]] + [line[indentation:] for line in func_lines]
)
body = body.strip().strip("\n")
return body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment