zachd1_618
zachd1_618

Reputation: 4350

Using (as of now) Undefined Functions in Lambda Functions in Python

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?

Upvotes: 4

Views: 321

Answers (1)

Max Noel
Max Noel

Reputation: 8910

You're defining getLambda and squareMe in separate modules. The lambdaSource module only sees what's defined in its scope -- that is, everything you define directly in it and everything you import in it.

To use squareMe from getLambda, you need lambdaSource.py to have a from runMe import squareMe statement (and not the other way around as you seem to be doing).

Upvotes: 3

Related Questions