trouble with reload

Carl Banks pavlovevidence at gmail.com
Fri Aug 14 08:31:19 CEST 2009


On Aug 13, 10:36 pm, "Dr. Phillip M. Feldman" <pfeld... at verizon.net>
wrote:
> Actually, I've tried both of these, and I get (different) errors in both
> cases:
>
> In [1]: from mymath import *
>
> In [2]: reload(mymath)
> NameError: name 'mymath' is not defined
>
> In [3]: reload('mymath')
> TypeError: reload() argument must be module

Two problems here.

1. You have to call reload on an actual module object.  When you write
"from mymath import *" you are not actually binding the mytmath module
to the mymath symbol.  So, if you were to then write "print mymath"
Python would raise a NameError exception.

OTOH, if you were to write "import mymath", then the symbol mymath
would bound to the mymath module.  If you then write "print mymath",
Python would output <module 'mymath' from '/wherever'>, the module
object.  Only then can you pass it to reload.

2. If you use "from mymath import *", even if you were to reload the
mymath module (say, by importing it directly and calling reload on
that), you will find that the functions you had originally imported
will not be updated.  They will still refer to the old functions.
Why?  Because when you reload a module, it only affects that's
module's namespace.  When you import a function from a module, you are
now referencing the function from your own namespace.  Even if the
function in the module is replaced, the reference to that function in
your own namespace hasn't been replaced.

So, what do you do?

My advice is to dispense with importing functions altogether; only
import modules.  It's more typing and a bit less efficient, but it
makes everything more straightforward and consistent.


Carl Banks



More information about the Python-list mailing list