Reloading module giving NameError: name 'reload' is not defined

PythonPython 3.x

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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:

Solution 2 - Python

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)

Solution 3 - Python

import imp
imp.reload(script4)

Solution 4 - Python

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

Solution 5 - Python

I recommend using the following snippet as it works in all python versions (requires six):

from six.moves import reload_module
reload_module(module)

Solution 6 - Python

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.....

Solution 7 - Python

For python2 and python3 compatibility, you can use:

# Python 2 and 3
from imp import reload
reload(mymodule)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLonnie PriceView Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonKevinView Answer on Stackoverflow
Solution 3 - Pythonuser57823View Answer on Stackoverflow
Solution 4 - PythonJoey WilhelmView Answer on Stackoverflow
Solution 5 - PythonAlleoView Answer on Stackoverflow
Solution 6 - Pythonuser6830669View Answer on Stackoverflow
Solution 7 - PythonPatrick José PereiraView Answer on Stackoverflow