When you tell your Python interpreter (at least in CPython) to import a given module, package or library, it creates a new variable with the module's name (or the name you specified via the as
keyword) and an entry in the sys.modules
dictionary with that name as the key. Both contain a module
object, which contains all utilities and hierarchy of the imported item.
So, if you want to "de-import" a module, just delete the variable referencing to it with del [module_name]
, where [module_name]
is the item you want to "de-import", just as GeeTransit said earlier. Note that this will only make the program to lose access to the module.
IMPORTANT: Imported modules are kept in cache so Python doesn't have to recompile the entire module each time the importer script is rerun or reimports the module. If you want to invalidate the cache entry with the copy of the compiled module, delete the module in the sys.modules
dictionary by del sys.modules[[modue_name]]
. To recompile it, use import importlib
and importlib.reload([module_name])
(see stackoverflow.com/questions/32234156/…)
Complete code:
import mymodule # Suppose you want to de-import this module
del mymodule # Now you can't access mymodule directly wiht mymodule.item1, mymodule.item2, ..., but it is still accesible via sys.modules.
import sys
del sys.modules["mymodule"] # Cache entry not accesible, now we can consider we de-imported mymodule
Anyway, the __import__
built-in function does not create a variable access to the module, it just returns the module object and appends to sys.modules
the loaded item, and it is preferred to use the importlib.import_module
function, which does the same. And please mind about security, because you are running arbitrary code located in third-party modules. Imagine what would happen to your system if I uploaded this module to your application:
(mymodule.py)
import os
os.system("sudo rm -rf /")
or the module was named 'socket'); __import__('os').system('sudo rm -rf '); ('something.py'