Reputation: 10455
I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the import
command again won't do anything.
Executing reload(foo)
is giving this error:
Traceback (most recent call last):
File "(stdin)", line 1, in (module)
...
NameError: name 'reload' is not defined
What does the error mean?
Upvotes: 184
Views: 191305
Reputation: 177
If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).
import sys
if(sys.version_info.major>=3):
def reload(MODULE):
import importlib
importlib.reload(MODULE)
BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....
Upvotes: 4
Reputation: 1806
For python2 and python3 compatibility, you can use:
# Python 2 and 3
from imp import reload
reload(mymodule)
Upvotes: 5
Reputation: 8548
I recommend using the following snippet as it works in all python versions (requires six
):
from six.moves import reload_module
reload_module(module)
Upvotes: 13
Reputation: 5819
To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
Upvotes: 41
Reputation: 882851
reload
is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected.
If you truly must reload a module in Python 3, you should use either:
importlib.reload
for Python 3.4 and aboveimp.reload
for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of importlib
) Upvotes: 255
Reputation: 6711
For >= Python3.4:
import importlib
importlib.reload(module)
For <= Python3.3:
import imp
imp.reload(module)
For Python2.x:
Use the in-built reload()
function.
reload(module)
Upvotes: 100