print the code which defined a lambda function [duplicate]
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'
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.