Reload in Python interpreter

12,693

Solution 1

From http://docs.python.org/library/functions.html#reload :

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.

So, you should do something like:

from myapp import *
....
import myapp
reload(myapp)
from myapp import *

Solution 2

How can I reload when using from myapp import *?

You can't. This is one of the reasons why using from X import * is a bad idea.

Solution 3

With from myapp import *, you don't have a reference to your module in a variable name, so you can't use a variable name to refer to the module.

Of course, there's nothing preventing you from importing it again to get the reference to the module in a name you can use. Since it's already been imported once, it won't actually be imported again:

import myapp
reload(myapp)

You can also get the reference directly from sys.modules.

import sys
reload(sys.modules["myapp]")

Solution 4

To clarify Wooble's comment, using "from foo import *" brings everything from foo into the current namespace. This can lead to name collisions (where you unintentionally assign a new value to a name already in use) and can also make it harder to tell where something came from. While a few libraries are often used this way, it generally causes more problems than it is worth.

Also, since it has been brought into the current namespace it cannot simply be reloaded. It is generally better to keep it in a separate namespace (perhaps with a shorter convenience alias like just m). This allows you to reload (which is useful for testing, but rarely a good idea outside of testing) and helps keept he namespace pure.

Share:
12,693
xralf
Author by

xralf

Updated on June 08, 2022

Comments

  • xralf
    xralf about 2 years
    $ python
    >>> import myapp
    >>> reload(myapp)
    <module 'myapp' from 'myapp.pyc'>
    >>>
    

    ctrl+D

    $ python
    >>> from myapp import *
    >>> reload(myapp)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'myapp' is not defined
    

    Why this behaves differently? How can I reload when using from myapp import *?

  • Wooble
    Wooble about 12 years
    Importing and reloading the module won't actually re-bind any names that were bound with from foo import *. This may or many not make the reload useless.
  • xralf
    xralf about 12 years
    The reason I use reload() is because I change the source code of the module and test it and the reason I use from myapp import is because it saves me typing.
  • xralf
    xralf about 12 years
    It's not a bad idea when debugging. It saves typing.