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?
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side hold the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no.
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
What is a Lambda Function in Python? A lambda function is an anonymous function (i.e., defined without a name) that can take any number of arguments but, unlike normal functions, evaluates and returns only one expression.
The lambda function above is defined and then immediately called with two arguments ( 2 and 3 ). It returns the value 5 , which is the sum of the arguments.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With