python - Why do functions from a dynamically loaded module depend on where the module is stored? -


following this answer, using imp.new_module , exec dynamically load module , extract functions it. however, when store module in local variable, functions broken. here example:

import imp  mod = none func = none  code = """ = 42  def func():     print """  def main():     #global mod     global func     mod = imp.new_module("modulename")     exec code in mod.__dict__     func = mod.func  main() func() 

executing python 2.7.3 yields none: codepad. after uncommenting global mod line, making mod global, function works expected , prints 42: codepad.

what missing? why behaviour change when module stored in local variable?

the mod module local, , not referenced anywhere else. other objects in python, means cleaned when main exits. making global instead, reference module object kept.

when module cleaned up, globals set none (this done break reference cycles early, setting none optimisation prevent excessive rehashing due dictionary resizing). func object still has reference module globals dictionary, , sees a bound none now.

the normal procedure of importing module adds reference module object in sys.modules, keeping module alive until interpreter shutdown.

(in python 3.4, globals no longer rebound none (in cases), per safe object finalization; see pep 442).


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -