How to unimport a python module which is already i

2019-01-22 02:15发布

I'm quite new with NumPy/SciPy. But these days, I've started using it very actively for numerical calculation instead of using Matlab.

For some simple calculations, I do just in the interactive mode rather than writing a script. In this case, are there any ways to unimport some modules which was already imported? Unimporting might not needed when I write python programs, but in the interactive mode, it is needed.

2条回答
再贱就再见
2楼-- · 2019-01-22 03:07

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 *).

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-22 03:10

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

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)
查看更多
登录 后发表回答