If a module is being tested while in the midst of development, it has to
be reloaded into a running interpreter in order for its most current
version to be available to the interpreter. Use the reload()
function
for this. Note that although the initial import
is a statement,
meaning that there are no parentheses around what follows it, reload()
is a function, not a statement, and so there are parentheses around
it.
Ipython (v. 0.12) and the normal Python interpreter (v. 2.6.5) handle
this in slightly different ways. Supposing you have a program
my_module.py
whose functions you want to import, and you do so (as I
almost always do) using a shorter, alternate name, like "M":
>>> import my_module as M
If my_module
undergoes changes that you want to make use of, in the
regular Python interactive mode you have two choices: (1) you can
simply use
>>> reload(my_module)
<module 'my_module' from 'my_module.pyc'>
or (2) you can use alternate name you imported the module as:
>>> reload(M)
<module 'my_module' from 'my_module.pyc'>
Python accepts either name as the argument of reload()
, as shown by
its response.
In Ipython, however, only the second of these works (2):
In [1]: import my_module as M
# (now my_module undergoes changes that you want to make use of)
In [2]: reload(M)
Out[2]: <module 'my_module' from 'my_module.pyc'>
The first (1) will generate an error:
In [3]: reload(my_module)
NameError: name 'my_module' is not defined
In Python 3, reload()
has been assigned to the imp
module, for
functionality related to the import
statement. So it has to be called
as imp.reload()
.