4

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?

2
  • 2
    Can't you just make getLambda take 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. Commented Jul 21, 2015 at 1:11
  • To be clear, this example just illustrates the problem. Really, the lambda function comes from a static configuration.ini file, parsed by another python module, and passed to a higher level module for execution. Commented Jul 21, 2015 at 2:37

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense, but I also would think that with an interpretive language, the lambda would have the scope available to it at the time of execution
That has nothing to do with the way the language is implemented (btw, Python is bytecode-compiled, not interpreted). It's strictly a design decision: the lambda does, in fact, have access to everything in the enclosing scope. It's just that said scope is the module's scope (Python doesn't have a concept of truly global scope, aside from its builtins).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.