variables bound in moudules are None when module is not completely imported

Gabriel Genellina gagsl-py2 at
Wed Feb 25 20:18:00 EST 2009

En Wed, 25 Feb 2009 21:24:33 -0200, <chrysn at> escribió:
> On Wed, Feb 25, 2009 at 05:05:28PM -0200, Gabriel Genellina wrote:

>> I'd try to move all the global stuff in that module into a function,
>> "init". Importing the module will always succeed - you have to manually
>> call init() after importing it.
> i normally do that anyway and would also have done so here (afaik, it's
> best practice anyway), but this is in this case not possible as the
> modules in question are not under my control at all. as pep 299 has been
> turned down, this can't really be considered a bug of those files.

You might ask the module author for this feature... At least, try to move  
the "registration" at the end, after any code likely to raise exceptions.

> anyway, it would just be another workaround around the globals
> disappearing.
>> That makes a strange situation where the module doesn't exist in
>> sys.modules but its globals are still alive...
> is this a known bug?

Not that I know.

> i mean from a garbage collection / refcount point
> of view, at least everything that is still referenced somewhere should
> be preserved.

In older Python versions, an error when importing a module could leave a  
module object in sys.module partially initialized. That's very bad! Now,  
the entry in sys.modules is removed in such cases. Note that functions and  
classes defined inside a module don't have a reference to the module  
itself - their __module__ attribute is a string (although functions *do*  
have a reference to the module namespace, as you have remarked). So the  
entry in sys.modules is likely to be the last and only reference, and when  
it's removed, the module is deleted. This is a very tricky operation and  
at some stage involves setting all globals to None; if not were for any  
external references (like a callback registered somewhere else, as in your  
case) the module plus the functions and classes and objects defined inside  
it plus its global namespace, all of these should disappear, kaput, gone.

You should report it at -- I don't think this is  
likely to be "fixed" now, but at least it's on record. And when someone  
attempts to improve the module destruction sequence, there is a better  
chance this is taken into account too.

Gabriel Genellina

More information about the Python-list mailing list