Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload in Python interpreter

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

like image 470
xralf Avatar asked May 01 '12 17:05

xralf


People also ask

What is the use reload () in Python?

Python Programming The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.

How do you reload in Python 3?

In Python 3, reload was moved from builtins to imp. So to use reload in Python 3, you'd have to write imp. reload(moduleName) and not just reload(moduleName).


2 Answers

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.

like image 142
NPE Avatar answered Sep 23 '22 22:09

NPE


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 *
like image 44
aland Avatar answered Sep 19 '22 22:09

aland