Why do directly imported variables behave differently than those attached to imported module?

Duncan Booth duncan.booth at invalid.invalid
Wed May 4 04:44:36 EDT 2011


Chris Angelico <rosuav at gmail.com> wrote:

> Here's a side point. What types will hold a reference to the enclosing
> module (or at least its dictionary)? Would it be possible to use a
> from import to load a module, then "lose" the module even though
> you're using objects from it?
> 
> I am guessing that a function or class will hold such a reference,
> because otherwise it would be a bit awkward for them to use any sort
> of module-level state. Or do they not, and instead go look for their
> module in sys.modules?

A function object has a reference to the dictionary for the module in which 
it was defined; it needs this to access global variables. A class holds the 
name of the module but has no reference to the actual module itself.

Yes, it is quite possible to delete a module object, but it won't generally 
matter since any classes that are still referenced will prevent their 
methods being deleted and any functions or methods that are still 
accessible will keep the globals alive as long as required.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list