Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

How to unimport a python module which is already imported?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...