Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read a lambda function as a string?

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?

like image 509
Chris Avatar asked Jun 22 '15 15:06

Chris


People also ask

How do you read a lambda expression?

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.

What is lambda in string?

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.

How do you read lambda in Python?

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.

Can a lambda function return a value?

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.


1 Answers

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
like image 166
maccartm Avatar answered Sep 23 '22 13:09

maccartm