Issue1584

classification
Title: jython modules can't access __main__.__dict__ if they are run more than once
Type: behaviour Severity: normal
Components: Core Versions: 2.5.1
Milestone:
process
Status: closed Resolution: invalid
Dependencies: Superseder:
Assigned To: Nosy List: pjenvey, vgod
Priority: Keywords:

Created on 2010-03-28.03:13:17 by vgod, last changed 2010-04-04.19:38:51 by vgod.

Messages
msg5598 (view) Author: Tsung-Hsiang Chang (vgod) Date: 2010-03-28.03:13:15
I am trying to dynamically create functions in __main__ from a Jython module. The idea is illustrated as following.


---- module.py ----
class Foo:
  def func(self):
    pass

def setup():
  foo = Foo()
  __main__.__dict__["func"] = foo.func # redirects a global function "func" to an instance method foo.func

setup()
---- end of module.py ---

---- main.py -----
from module import *

func() # this should invokes aObject.func

---- end of main.py ----

I ran the above code simply using the following java code.

PythonInterpreter py = new PythonInterpreter();
py.execfile("main.py");
py.cleanup();

When I was running this code first time, everything worked fine. The weird thing was, if I ran the same thing again, I got a "NameError: name 'func' is not defined". 
I did some experiments and found I couldn't write anything into __main__ from a module after the first run. I tried to find a workaround, e.g. reload(module), but still failed.
msg5625 (view) Author: Philip Jenvey (pjenvey) Date: 2010-04-04.18:12:06
I assume module.py does an "import __main__" which was omitted from your paste.

If so then the 'module' module has imported __main__ as a top level object the first time. From then on it persists there in memory as a global. The second time you run the program it must reuse the same module object already loaded into memory.

reload() should work, depending on it's used, i.e.

import module
reload(module)
module.func()

Please reopen this bug if this doesn't work and you suspect it's jython's fault
msg5634 (view) Author: Tsung-Hsiang Chang (vgod) Date: 2010-04-04.19:38:50
Yes, I omitted an "import __main__", and I also tried reload(module). Unfortunately, it didn't work.
Btw, I found a weird thing afterward. If I reuse the same PythonInterpreter and do not create a new instance, the script works fine. But if I create a new PythonInterpreter instance every time before running the script, it fails after the first run.
I strongly suspect it's Jython's bug.
History
Date User Action Args
2010-04-04 19:38:51vgodsetmessages: + msg5634
2010-04-04 18:12:07pjenveysetstatus: open -> closed
resolution: invalid
messages: + msg5625
nosy: + pjenvey
2010-03-28 03:13:17vgodcreate