I'd like to read a lambda function I created as a string, after I created it.
For example,
func = lambda num1,num2: num1 + num2
I'd like to read func as:
'lambda num1,num2: num1 + num2'
Is there a way to accomplish this or even read any part of the lambda function?
Edit : Changed my first answer as I misunderstood the question. This answer is borrowed from a number of other uses, however I have completed the code to only display the part of the string that you want.
import inspect
func = lambda num1,num2: num1 + num2
funcString = str(inspect.getsourcelines(func)[0])
funcString = funcString.strip("['\\n']").split(" = ")[1]
print funcString
Outputs the following string:
lambda num1,num2: num1 + num2
You can use getsourcelines
from the inspect
module to do this
This function returns as a list all of the lines of the definition of any function, module, class or method as well as the line number at which it was defined.
For example:
import inspect
f = lambda x, y : x + y
print inspect.getsourcelines(f)[0][0]
Will output the definition of the function as:
f = lambda x, y: x + y
You can use Python's eval()
function:
>>> func = eval('lambda num1,num2: num1 + num2')
>>> func
<function <lambda> at 0x7fe87b74b668>
To evaluate any expression and return the value.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.