Python really should have a way to lambda-lift a value e to a no-argument callable function which returns e. Let us suppose that our e is denoted by the variable alpha
. One can approximate such a lifting by declaring alpha_fnc = lambda: alpha
. Python lambdas are slow compared to true currying functionality, like provided by functools.partial
and the functions of the operator
library, but it basically works. The problem, however, is that lambda declarations in Python, unlike in, say, C++ 11, have no closure mechanism to capture the local scope, so lambda which refer to outer variables are context-dependent. The following interactive session illustrates the problem.
In [1]: alpha_fnc = lambda: alpha In [2]: alpha_fnc() ------------------------------------------------------------------------ NameError Traceback (most recent call last) Input In [2], in () ----> 1 alpha_fnc() Input In [1], in () ----> 1 alpha_fnc = lambda: alpha NameError: name 'alpha' is not defined In [3]: alpha = .5 In [4]: alpha_fnc() Out[4]: 0.5 In [5]: alpha = .4 In [6]: alpha_fnc() Out[6]: 0.4