How do you read a lambda function as a string?
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 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 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