Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print the code which defined a lambda function [duplicate]

Tags:

python

I'd like to be able to print the definition code of a lambda function.

Example if I define this function through the lambda syntax:

>>>myfunction = lambda x: x==2 >>>print_code(myfunction) 

I'd like to get this output:

x==2 
like image 545
Mapad Avatar asked Dec 02 '08 17:12

Mapad


People also ask

How do you duplicate a lambda function?

There is no provided function to copy/clone Lambda Functions and API Gateway configurations. You will need to create new a new function from scratch. If you envision having to duplicate functions in the future, it may be worthwhile to use AWS CloudFormation to create your Lambda Functions.

Can lambda function be reused in Python?

Can we reuse the lambda function? I guess the answer is yes because in the below example I can reuse the same lambda function to add the number to the existing numbers.

How can I access the output of print statements from lambda?

Navigate to the monitoring tab of your lambda function and click the “view logs in CloudWatch” button. You should now be inside CloudWatch viewing your log output.


2 Answers

As long as you save your code to a source file you can retrieve the source code of an object using the inspect module.

example: open editor type:

myfunction = lambda x: x==2 

save as lamtest.py

open shell type python to get to interactive python type the following:

>>>from lamtest import myfunc >>>import inspect >>>inspect.getsource(myfunc) 

the result:

'myfunc = lambda x: x==2\n' 
like image 136
pcn Avatar answered Sep 22 '22 17:09

pcn


It will only work for mathematical based operations, but you might look at SymPy's Lambda() object. It was designed exactly for this purpose:

>>> from sympy import * >>> x = Symbol('x') >>> l = Lambda(x, x**2) >>> l Lambda(_x, _x**2) >>> l(3) 9 

It even supports pretty printing:

>>> pprint(l)  ⎛    2⎞ Λ⎝x, x ⎠ 

To do your equals example, us the SymPy Eq() object:

>>> l1 = Lambda(x, Eq(x, 2)) >>> l1 Lambda(_x, _x == 2) >>> l1(2) True 

It supports partial argument expansion:

>>> y = Symbol('y') >>> l2 = Lambda((x, y), x*y + x) >>> l2(1) Lambda(_y, 1 + _y) >>> l2(1, 2) 3 

And of course, you get the advantage of getting all of SymPy's computer algebra:

>>> l3 = Lambda(x, sin(x*pi/3)) >>> pprint(l3(1))   ⎽⎽⎽ ╲╱ 3  ─────   2   

By the way, if this sounds like a shameless plug, it's because it is. I am one of the developers of SymPy.

like image 45
asmeurer Avatar answered Sep 20 '22 17:09

asmeurer