Sometimes while working, we want to remove a previously imported module. We can use some methods, such as using the
del statement or
pop() methods, to achieve the goal. This article will explain it in detail. Let’s find out.
Remove an imported module in Python.
There are several ways to Remove an imported module in Python. We’ll go through each approach and how it’s used.
Use “del” statement
del keyword is used to delete objects in Python programming language. Because everything in this language is an object, the
del keyword was created to make it easy to delete objects such as strings, numbers, Lists, etc.
name = "John" # The variable name is deleted and no longer exists del name print(name)
NameError: name 'name' is not defined
There’s no way to unload anything you accidentally imported into Python. Because Python will save a copy in temporary memory, so you will use
del statement to disconnect from that module.
Use the statement “del” placed in front of the module you want to remove the connection.
When you try to reapply the module that you lost connection with, Python will utilize the cached version, thus you must use the “reload()” function to update the module again.
import importlib # Use "reload()" to update the module importlib.reload(module)
del statement can also be used to delete modules from the “sys.modules” dictionary
import sys import numpy # Use "del" statement to delete modules from the "sys.modules" dictionary del sys.modules['numpy']
Use the “pop()” method
pop() is a method used to delete an item from a dictionary, it can also be used on a List object. The return value of this method will be the item it removed.
key: is the key of the item you want to delete in the dictionary
defaultvalue: If the key you passed does not exist, this default value will be returned.
The value of the item deleted from the dictionary will be returned
When you import a module, the module will be saved into the “sys.modules” dictionary so that we can use the
pop() method to unimport. “sys.modules” is a dictionary that stores all the module names that have been imported.
import sys # Use the "pop()" method to unimport sys.modules.pop("module name")
You still have to use the
reload() method if you want to import again. If you don’t update the module, Python will still use the old code you imported before.
We learned how to remove an imported module in Python through the article. Modules cannot be completely removed once imported, but we can only not refer to them. Hope this article is helpful to you.
Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).