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


i define lambda function in different module executed in. in module lambda called, there methods available aren't when lambda defined. is, python throws error when lambda tries employ functions.

for example, have 2 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 run runme.py, name error: nameerror: global name 'squareme' not defined

the way can around modify lambda's global variables dictionary @ runtime.

thelambdafunc.func_globals['squareme'] = squareme 

this example contrived, behavior desire. can explain why first example doesn't work? why 'squareme' isn't available scope of lambda function? when, if defined lambda below function squareme, works out okay?

you're defining getlambda , squareme in separate modules. lambdasource module sees what's defined in scope -- is, define directly in , import in it.

to use squareme getlambda, need lambdasource.py have from runme import squareme statement (and not other way around seem doing).


Comments