如何取消导入已经导入的 Python 模块?

我对 NumPy/SciPy 还是个新手。但最近,我开始非常积极地使用它进行数值计算,而不是使用 Matlab。

对于一些简单的计算,我只是在交互模式下进行,而不是编写脚本。在这种情况下,是否有任何方法来取消导入一些已经导入的模块?在编写 python 程序时,可能不需要取消导入,但在交互模式下,需要取消导入。

94678 次浏览

While you shouldn't worry about "unimporting" a module in Python, you can normally just simply decrement the reference to the imported module or function using del:

>>> import requests
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'readline', 'requests', 'rlcompleter']
>>> del requests
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'readline', 'rlcompleter']
>>>

Note that I'd advise just not worrying about this as the overhead of an unused import is near trivial -- traversing one extra entry in sys.modules is nothing compared to the false security del some_module will give you (consider if the __init__ does some setup or you ran from X import *).

There's no way to unload something once you've imported it. Python keeps a copy of the module in a cache, so the next time you import it it won't have to reload and reinitialize it again.

If all you need is to lose access to it, you can use del:

import package
del package

Note that if you then reimport the package, the cached copy of the module will be used.

If you want to invalidate the cached copy of the module so that you can re-run the code on reimporting, you can use sys.modules.pop instead as per @DeepSOIC's answer.

If you've made a change to a package and you want to see the updates, you can reload it. Note that this won't work in some cases, for example if the imported package also needs to reload a package it depends on. You should read the relevant documentation before relying on this.

For Python versions up to 2.7, reload is a built-in function:

reload(package)

For Python versions 3.0 to 3.3 you can use imp.reload:

import imp
imp.reload(package)

For Python versions 3.4 and up you can use importlib.reload:

import importlib
importlib.reload(package)

When you import a module, Python looks if this module is in sys.modules dictionary. If not, it runs the module, and puts the resulting module object in sys.modules.

So, to unimport a module, one might use

import sys
sys.modules.pop('your_module_name_here')

The next time it is imported, Python will re-execute the module. However, in all other loaded modules that have imported the module, the old code will still be used, as they still hold the reference to the old module object. reload function explained in other answers helps with that situation by updating the module object rather than creating a brand new one. But it doesn't help with from your_module import some_function style of imports.

My suggestion is that you have to find all relevant/children import with that module to remove them successfully.

package_name = your_package_name
loaded_package_modules = [key for key, value in sys.modules.items() if package_name in str(value)]
for key in loaded_package_modules:
print(key)
del sys.modules[key]