3

Just out of curiosity, how would one go about un-importing a module?

For example, you import a couple of modules like this:

import x, y, z

Then say for some reason you don't want and / or need module y to be included anymore, how would you only un-import module y without affecting modules x or z?

Thank you in advance.

  • 6
    [You don't](https://stackoverflow.com/questions/3105801/unload-a-module-in-python) – Cory Kramer Jun 08 '16 at 11:57
  • I'm not sure what you're asking but if your code doesn't refer to module y any more you would just do: import x, z basically this is just shorthand for import x import y import z – Keef Baker Jun 08 '16 at 12:01
  • 1
    The only thing you can do is to throw away the reference with `del y` but there's no real unloading involved. – Matthias Jun 08 '16 at 12:27

1 Answers1

2

From the docs:

Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs).

If you need a module temporarily and you are concerned about cluttering the global namespace you can import in a local scope and the global namespace won't be affected.

AFAIK, the first step of the import statement cannot be undone.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75