NameError: name 'reload' is not defined in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
2 min

banner

# NameError: name 'reload' is not defined in Python [Solved]

The "NameError: name 'reload' is not defined" occurs when we use the reload() function without importing it.

To solve the error, import the reload function from the built-in importlib module before using it.

python nameerror name reload is not defined

Here is an example of how the error occurs.

main.py
import glob # ⛔️ NameError: name 'reload' is not defined new = reload(glob)

how the error occurs

# Import the reload function before using it

To solve the error, import the reload function from the built-in importlib module before using it.

main.py
import glob import importlib new = importlib.reload(glob) print(new) # 👉️ <module 'glob' (built-in)>

import reload from importlib

The code for this article is available on GitHub
In Python version 2, the reload() function was built-in and directly accessible, however, in Python 3 it has been moved to the importlib module.

# Importing only the reload function from the importlib module

The code sample imports the entire importlib module, however, you can also import only the reload() function from the module.

main.py
import glob from importlib import reload new = reload(glob) print(new) # 👉️ <module 'glob' (built-in)>

import only the reload function

The code for this article is available on GitHub

The importlib.reload() method reloads a previously imported module.

The argument to the method must be a module object that has been successfully imported (prior to reloading it).

The importlib.reload() method is most often used when we have edited the source of the module using an external editor and we want to get access to the newer version without exiting the interpreter.

The reload() method returns the module object, so you can directly reassign the module to the result of calling reload(module).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.