Module gets garbage collected; its globals become None

Steven Taschuk staschuk at telusplanet.net
Sat May 24 07:43:57 EDT 2003


Quoth "Martin v. Löwis":
> Steven Taschuk wrote:
> 
> > So much for *how* this occurs.  What I'm curious about is why --
> > why do the dict's values have to be cleared when the module is
> > collected?  Why not just let the dict, and hence its values, get
> > collected in its turn?
> 
> Historically, this was there to break cycles between modules,
> when there was no cyclic garbage collection.

Hm... and the dict is involved in cycles even within a single
module, I now notice:

    # spam.py
    x = 3
    def eggs():
        return x

    >>> import spam
    >>> d = spam.__dict__
    >>> d['eggs'].func_globals is d
    True

Breaking such cycles by clearing the dict's values makes sense at
shutdown; but doing so during module collection allows the
namespace to be nuked when live objects still depend on it:

    >>> import imp
    >>> mod = imp.new_module('foo')
    >>> execfile('spam.py', mod.__dict__)
    >>> mod.eggs()
    3
    >>> f = mod.eggs
    >>> del mod
    >>> f()
    >>> 

Is the assumption that modules only ever get collected at shutdown?

> [...] Shutdown is a really tricky thing in Python, [...]

Yes, a glance at PyImport_Cleanup convinced me of that!

My primary interest here is not so much the shutdown procedure as
"routine" collection of modules in the middle of execution, as in
the example above.

  [...]
> > And if so, couldn't this equally as well be done by
> > giving modules' dicts their own tp_dealloc, one which clears them
> > in the desired order?
> 
> Not sure what you are suggesting here.

Well, since I wrote that I've come to see that the idea doesn't
make much sense.  (I was overlooking the func_globals cycles, for
one thing, and thus naïvely expecting the dict to be collected
before its contents.)  Scratch that idea.

  [...]
-- 
Steven Taschuk                            staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
                                                  (Kinsley's Law)





More information about the Python-list mailing list