Skip to content

Instantly share code, notes, and snippets.

@noklam
Created February 1, 2024 13:58

Revisions

  1. noklam created this gist Feb 1, 2024.
    17 changes: 17 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    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