Confusing behaviour relating to module objects being GCed.

Troels Therkelsen t_therkelsen at hotmail.com
Tue Jun 10 10:50:39 EDT 2003


Hello helpful people at c.l.py :-)

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 (it probably can be reduced further by the more
Python-savvy than yours truly):

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 an 'external'
ref to the module which is deleted from mone, everything is fine.

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

Best regards,

Troels Therkelsen





More information about the Python-list mailing list