116

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.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
chanwcom
  • 4,420
  • 8
  • 37
  • 49
  • but name space ? maybe got external source ? need deep scan... – dsgdfg Aug 26 '15 at 18:35
  • Sake of argument, is there a reason you can't restart the CLI when you need to reset the imports? – Frank V Aug 26 '15 at 18:35
  • why would you ever need in unimport a module? not saying you don't, I just can't think of a reason... – lollercoaster Aug 26 '15 at 18:37
  • you can use the import-as syntax if you want to allocate a different name to deal with command conflicts. For eg: `import numpy as np` – stanri Aug 26 '15 at 18:39
  • You want to check out this answer: [http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module][1] [1]: http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module – daf Aug 26 '15 at 18:43
  • 1
    https://stackoverflow.com/questions/43181440/what-does-del-sys-modulesmodule-actually-do#43181488 is a solution with caveats using `del sys.modules['foo']`. – Robert Fleming Jan 23 '18 at 03:12
  • @lollercoaster After `from __future__ import print_function` you can use `print (*a)` but if you are doing some tests and want to revert back so `print (*a)` is SyntaxError you might want to unimport the module. – Chupo_cro Mar 28 '18 at 03:15

4 Answers4

145

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    Would this clear the dictionary with the names of available functions? – MadPhysicist Dec 28 '17 at 14:43
  • @MadPhysicist not sure what you're asking. – Mark Ransom Dec 28 '17 at 16:51
  • I think what I am asking is this. Suppose you do `import numpy as np` and then `np.pi = 2`. How can I reset the things in Python to either `n.pi = 3.14 ..` state or the state where `numpy` has not been imported yet. In short, can one fully undo the import without reloading the Python or console? – MadPhysicist Dec 29 '17 at 01:17
  • @MadPhysicist I would expect that `reload` would re-initialize the entire contents of the module, undoing any changes you've made to it. Have you tried it? – Mark Ransom Dec 29 '17 at 03:48
  • This method might not override other modules' references to the reloaded module. See https://stackoverflow.com/a/61617169/2642356 for a solution to that. – EZLearner May 05 '20 at 15:59
38

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
DeepSOIC
  • 503
  • 4
  • 5
  • 4
    i think this is a better answer than `del` since it invalidates the import cache, which is what I almost always want in these types of situations ... – maxymoo Jun 29 '21 at 00:59
  • 1
    @maxymoo you might need to do both. Python is more than happy to keep an old version of the module even after you import a new one, as long as a reference to it exists. – Mark Ransom Mar 11 '22 at 19:01
16

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

5

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]
dtlam26
  • 1,410
  • 11
  • 19