Created
December 1, 2022 06:56
-
-
Save secemp9/3a30ccd9718ee88abbedf4ab1ed24b65 to your computer and use it in GitHub Desktop.
bring dependencies with your function! (experimental)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import ast | |
from itertools import dropwhile | |
import types | |
def get_function_body(func, strip_def=True):# needs recursive function listing, so can support sending nested function/etc | |
if not strip_def: | |
return "".join(inspect.getsourcelines(func)[0]) | |
source_lines = inspect.getsourcelines(func)[0] | |
source_lines = dropwhile(lambda x: x.startswith('@'), source_lines) | |
line = next(source_lines).strip() | |
if not line.startswith('def '): | |
return line.rsplit(':')[-1].strip() | |
elif not line.endswith(':'): | |
for line in source_lines: | |
line = line.strip() | |
if line.endswith(':'): | |
break | |
# Handle functions that are not one-liners | |
first_line = next(source_lines) | |
# Find the indentation of the first line | |
indentation = len(first_line) - len(first_line.lstrip()) | |
return ''.join([first_line[indentation:]] + [line[indentation:] for line in source_lines]) | |
def test1(): | |
return "World" | |
def test2(): | |
print("Hello") | |
print(test1()) | |
def test3(): | |
print("maybe") | |
print(test1()) | |
print(test2()) | |
notsure = [] | |
for i in ast.walk(ast.parse("".join(inspect.getsourcelines(test3)[0]))): | |
try: | |
if isinstance(i, ast.Call) and not isinstance(eval(i.func.id), types.BuiltinFunctionType) and not isinstance(eval(i.func.id), type): | |
if i.func.id in notsure: # not using a set to keep the order | |
pass | |
else: | |
notsure.append(i.func.id) | |
except: | |
pass | |
for j in notsure[:-1]: | |
print(get_function_body(eval(j), strip_def=False)) | |
print(get_function_body(eval(notsure[-1:][0]), strip_def=True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment