How to unimport a python module which is already imported?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python does not have a true “unimport” operation that fully rewinds module execution. Once a module has been imported, it is cached in sys.modules, and any existing references to its objects keep living in memory. What you can do is remove the module from your namespace, remove it from sys.modules, and then re-import it later if needed. That is an approximation, not a perfect undo.
What an Import Actually Does
When Python imports a module, it executes the module code and stores the resulting module object in sys.modules. Future imports usually reuse that cached module instead of executing the file again.
That cache is the reason there is no single built-in unimport() function. Python assumes imported modules are part of a long-lived interpreter process.
Remove the Local Name vs Remove the Module Cache
These two operations are different.
Removing the local name only deletes one reference:
After that, the name math is gone from the current namespace, but the module is still present in sys.modules.
Removing the cache entry looks like this:
That makes a future import math eligible to load the module again, but it still does not destroy any references held elsewhere.
A Practical “Unimport” Pattern
If you want the closest approximation, do both operations.
This can be useful in experiments, plugin systems, or specific test scenarios where you want to reload import-time behavior.
Why This Does Not Fully Reset State
Suppose another module imported math earlier, or your code saved a function object from the target module. Those references remain valid even if you pop the module from sys.modules.
The same problem applies to side effects. If the module changed global configuration, opened files, registered signal handlers, or mutated singletons during import, removing the cache entry will not undo those actions.
That is why unimporting is rarely the best primary design.
Use importlib.reload When You Just Need Fresh Code
If your goal is to re-run module code during development, importlib.reload is often more appropriate than pretending the module was never imported.
Reloading has its own caveats, but it is a clearer tool when the real need is “refresh the module implementation.”
For Reliable Isolation, Use a New Process
If you need a truly clean import state, the dependable answer is a new Python process. Test runners, subprocess-based tools, and isolated worker processes solve this better than aggressive manipulation of sys.modules.
A new interpreter starts with a fresh module cache. That is the only complete reset.
Common Pitfalls
- Assuming
del module_nameunloads the module completely. - Removing an entry from
sys.moduleswhile other code still holds references to the module or its objects. - Expecting import-time side effects to be reversed automatically.
- Using cache removal where
importlib.reloadwould better express the intent. - Trying to fake interpreter isolation inside a long-running process.
Summary
- Python has no true built-in operation that fully unimports a module.
- Deleting a local name and removing
sys.modulesentries are different actions. - The closest approximation is to remove both the namespace reference and the cache entry.
- Existing references and side effects remain even after cache removal.
- For full isolation, start a new Python process instead of relying on unimport tricks.
Related reading
- How to uninstall a package installed with pip install --user
- How to uninstall Python 2.7 on a Mac OS X 10.6.4?
- How to unnest explode a column in a pandas DataFrame, into multiple rows
- How to unpack pkl file
- How to unzip a folder in google colab?
- How to unzip a list of tuples into individual lists?
- How to update a plot in matplotlib
- How to update an existing Conda environment with a .yml file
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.