Skip to content

Instantly share code, notes, and snippets.

@secemp9
Last active November 30, 2022 17:22
Show Gist options
  • Save secemp9/3999e73f5537739d140f6a05acee9179 to your computer and use it in GitHub Desktop.
Save secemp9/3999e73f5537739d140f6a05acee9179 to your computer and use it in GitHub Desktop.
define function with dependent function if called locally/inside
import inspect
l = []
copy_dict = dict(locals())
for key, value in copy_dict.items():
if "function" in str(value) and callable(value) and value.__module__ == __name__:
l.append(key)
# print(l)
def increment_indent(a):
b = a.splitlines()
# hmm = set()
for i in b:
leading_spaces = len(i) - len(i.lstrip())
# hmm.add(leading_spaces)
# get smallest number here, if it's 4, 8, or 2, then use that as indentation for everything
uh = ""
for i in b:
uh += 4 * " " + i
uh += "\n"
return uh
def test1():
return "World"
def test2():
print("Hello")
print(test1())
l = []
copy_dict = dict(locals())
for key, value in copy_dict.items():
if "function" in str(value) and callable(value) and value.__module__ == __name__:
l.append(key)
def function_merger(x):
total = ""
source_lines = inspect.getsourcelines(x)[0]
for i in source_lines:
if i.startswith("def "):
ah = source_lines
for j in l:
if j in "".join(ah[1:]):
for g in source_lines:
if j in g:
total += increment_indent("".join(inspect.getsourcelines(eval(j))[0]))
total += g
else:
total += g
return total
# output:
"""
def test2():
print("Hello")
def test1():
return "World"
print(test1())
"""
print(function_merger(test2))
# wanted result:
"""
def test2():
print("Hello")
def test1():
return "World"
print(test1())
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment