You can use Python's inspect
module to get the desired code as a list of strings:
#!/usr/bin/env python3
# coding: utf-8
import inspect
func = lambda num1, num2: num1 + num2
def f():
a = 1
b = 2
return a + b
def get_code_as_string(passed_func):
return inspect.getsourcelines(passed_func)
if __name__ == '__main__':
# feed a lambda function
print(get_code_as_string(func))
# feed a normal function
print(get_code_as_string(f))
The output is as follows:
(['func = lambda num1, num2: num1 + num2\n'], 6)
(['def f():\n', ' a = 1\n', ' b = 2\n', ' return a + b\n'], 8)
As you can see inspect.getsourcelines()
returns a tuple of a list and an integer. The list contains all the lines of the function passed to inspect.getsourcelines()
and the integer represents the line number in which the provided functions starts.