Another (perhaps similar) import question

Gary Herron gherron at islandtraining.com
Fri Jun 13 20:00:16 EDT 2008


Dan Yamins wrote:
> I also have noticed another (to me) strange thing about module 
> imports.  If anyone could explain this to me, that would be great (I 
> apologize if it's too elementary for this list.)
>
> Suppose I have a module
>
>   #file: testmodule.py
>   a = 1
>
>
> When importing this module, obviously 'a' becomes an attribute of 
> testmodule:
>
>   >>> import testmodule
>   >>> dir(testmodule)
>   ['__builtins__', '__doc__', '__file__', '__name__', 'a']
>
>
> Now, supposed I modify the file to:
>
>   #file: testmodule.py
>   A = 1
>
> and then reload:
>
>   >>> reload(testmodule)
>   <module 'testmodule' from 'testmodule.py'>
>
> Now, the reported attributes still include the old 'a':
>
>   >>> dir(testmodule)
>   ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a']
>
> Why does this happen?

Because loading (and reloading) assigns values to variables (called 
binding a value in Python), but does not go on a hunt to find variables 
to *unbind*.   Once a variable is bound to a value, it stays bound until 
something unbinds or rebinds it, and module loading does no such thing.


>
> Moreover, even if I delete the module from memory and then reload, I 
> _still_ get the old attribute 'a':

But in fact you did *not* delete the module from memory.  A module 
import goes through two phases, only one of which you have access to...

Phase 1.  Read/parse/execute each statement, and keep the resulting 
namespace internally adn hidden from the user.  (This is only done once.)

Phase 2.  Bind the module to a local name. (This may be done many times)

This
  import xyz
may or may not cause module xyz to be read/parsed/run (depending of 
whether it's the first time imported or not), and then it binds the 
resulting module namespace to the variable xyz.  Your del of the module 
just removed the one reference to it, but that's all.
>
>   >>> del testmodule
>   >>> import testmodule
>   >>> dir(testmodule)
>   ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a']
>
> What is the principle behind this? And, is there some simple way 
> (other than restarting the interpreter) of "reloading" that wipes out 
> the old attributes associated with a given name so that spurious 
> attributes do not remain?

No.

Conclusion:  Don't use reload (ever).  A dozen years of Python 
programming, and I've never used it even once.   If there is a good use 
case for reload, you are probably years from being there.

>
> Thanks again (and apologies of this is a stupid question)

Not stupid.  It will all start making sense soon.

Gary Herron

>
> Dan
>
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list