[Python-Dev] Confusing behaviour relating to module objects being GCed.

Troels Therkelsen troels@2-10.org
Fri, 13 Jun 2003 16:14:17 +0200


Hello Python-Dev,

First off, I apologise if it is inappropriate to post this question here --
feel free to tell me to buzz off ;-).  As far as introductions go, I'm just
one of the thousands of average Python users, and I am feeling a little
uncertain about posting to this mailinglist, but I really want to understand
what's going on.  I did post this message to c.l.py and nobody has seemed
to care to actually try to explain what is happening.

Anyway, I'm having a problem in a large framework relating to using custom
__import__ and reload hooks.  I've been able to reduce the code that
demonstrates this problem to this Python code:

Python 2.3b1 (#1, Apr 27 2003, 22:07:38)
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import new
>>> mone = new.module('mone')
>>> mone.mtwo = new.module('mtwo')
>>> mone.mtwo.var = 42
>>> exec "def func():\n  print var\n  delmtwo()\n  print var\n" in
mone.mtwo.__dict__
>>> def delmtwo():
...   delattr(mone, 'mtwo')
...
>>> mone.mtwo.delmtwo = delmtwo
>>> mone.mtwo.func()             # FIRST CASE
42
None
>>> mone.mtwo = new.module('mtwo')
>>> mone.mtwo.var = 42
>>> exec "def func():\n  print var\n  delmtwo()\n  print var\n" in
mone.mtwo.__dict__
>>> keepref = mone.mtwo
>>> mone.mtwo.delmtwo = delmtwo
>>> mone.mtwo.func()             # SECOND CASE
42
42

The problem is that after mone.mtwo.func() calls delmtwo() which removes the
mtwo module from mone and thus reduces the ref-count to 0 (in the first
case),
func.im_func.func_globals starts showing a very peculiar behaviour.
Basically,
all of the module-level variable *names* stay, but all the *values* become
None.  As the second call to func() demonstrates, if I keep a ref to the
module which is deleted from mone, everything is fine.

I am at a loss explaining this behaviour (not knowing anything about Python
internals) and I would greatly appreciate enlightment that either confirms
that this is a bug, or explains why it isn't :-)

Of course, if it is indeed a bug, I'll report it to Sourceforge... I just
don't
want to report it if it isn't.

Best regards,

Troels Therkelsen