Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 above
  • imp.reload for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of importlib)

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)

import imp
imp.reload(script4)

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

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

from six.moves import reload_module
reload_module(module)

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


For python2 and python3 compatibility, you can use:

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