I would like to define a lambda function in a different module than it will be executed in. In the module that the lambda will be called, there are methods available that aren't when the lambda is defined. As it is, Python throws an error when the lambda tries to employ those functions.
For example, I have two modules.
lambdaSource.py:
def getLambda():
return lambda x: squareMe(x)
runMe.py
import lambdaSource
def squareMe(x):
return x**2
if __name__ == '__main__':
theLambdaFunc = lambdaSource.getLambda()
result = theLambdaFunc(5)
If you run runMe.py, you get a Name Error: NameError: global name 'squareMe' is not defined
The only way I can get around this is to modify the lambda's global variables dictionary at runtime.
theLambdaFunc.func_globals['squareMe'] = squareMe
This example is contrived, but this is the behavior I desire. Can anyone explain why the first example doesn't work? Why 'squareMe' isn't available to the scope of the lambda function? Especially when, if I just defined the lambda below the function squareMe, everything works out okay?
getLambdatake an argument and pass in the function, e.g.getLambda(f): return lambda x: f(x)? I can't see why you would need to do it the way you're doing it now.