Remove an imported module in Python

avatar

Borislav Hadzhiev

Last updated: Jul 7, 2022

banner

Photo from Unsplash

Remove an imported module in Python #

To remove an imported module in Python:

  1. Use the del statement to delete the sys reference to the module.
  2. Use the del statement to remove the direct reference to the module.
main.py
import sys import requests # 👇️ <function get at 0x7f8c7d30e4d0> print(requests.get) # ✅ remove imported module del sys.modules['requests'] del requests # ⛔️ NameError: name 'requests' is not defined print(requests.get)

The first step is to delete the sys.modules reference to the module we are trying to unload.

Sys.modules is a dictionary that maps module names to modules that have already been loaded.

The dictionary is most commonly used to force reload modules.

This is necessary because even if we delete the direct reference to the module, we'd still have a reference to it with the sys.modules dictionary.
main.py
import sys import requests # 👇️ <function get at 0x7f8c7d30e4d0> print(requests.get) del requests # 👇️ <module 'requests' from '/home/borislav/Desktop/bobbyhadz_python/venv/lib/python3.10/site-packages/requests/__init__.py'> print(sys.modules['requests'])

For the module to get garbage collected, we have to delete the key from the sys.modules dictionary and delete the direct reference to the module.

It can sometimes be tricky to unload a module. An alternative you can try is to reload the module using the importlib.reload() method.

main.py
from importlib import reload import requests if len('a') == 1: requests = reload(requests) # 👇️ <function get at 0x7f5cddf024d0> print(requests.get)

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.