Usage (for now) Undefined Functions in lambda functions in Python

I would like to define a lambda function in a different module than how it will be executed. In the module that will be called by the lambda, there are available methods that are not when the lambda is defined. Be that as it may, Python generates an error when the lambda tries to use these 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 will receive an error message:NameError: global name 'squareMe' is not defined

The only way I can get around this is to change the dictionary of global lambda variables at runtime.

theLambdaFunc.func_globals['squareMe'] = squareMe

, , . - , ? "squareMe" -? , , squareMe, ?

+4
1

getLambda squareMe . lambdaSource , - , , , import .

squareMe getLambda, lambdaSource.py from runMe import squareMe ( , , , ).

+3

Source: https://habr.com/ru/post/1598787/


All Articles