By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,876 Members | 1,542 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,876 IT Pros & Developers. It's quick & easy.

Re: Another (perhaps similar) import question

P: n/a
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

a = 1
When importing this module, obviously 'a' becomes an attribute of
>>import testmodule
['__builtins__', '__doc__', '__file__', '__name__', 'a']
Now, supposed I modify the file to:

A = 1

and then reload:
<module 'testmodule' from ''>

Now, the reported attributes still include the old 'a':
['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)

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
['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?

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


Jun 27 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.