Another (perhaps similar) import question

Dan Yamins dyamins at gmail.com
Sat Jun 14 01:32:28 CEST 2008


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?

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

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

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

Dan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080613/ad7ba44f/attachment.html>


More information about the Python-list mailing list