How To Remove an Imported Module in Python

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

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

Example:

name = "John"

# The variable name is deleted and no longer exists
del name
print(name)

Output:

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.

Example:

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

Example:

import importlib

# Use "reload()" to update the module
importlib.reload(module)

The del statement can also be used to delete modules from the “sys.modules” dictionary

Example:

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.

Syntax:

dictionary.pop(key, defaultvalue)

Parameter:

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.

Return Value:

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. 

Example:

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.

Summary

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.

Leave a Reply

Your email address will not be published. Required fields are marked *