9

It's clear to me that there was no clean solution in Python 2 to unload a module, and this was a known bug, that was set to be corrected.

The posts:

How do I unload (reload) a Python module? Remove an imported python module

of the year 2009 and 2010 confirm this lack of support for unloading a module.

I wonder if this was solved in Python 3.x. When I do, import os, del os, dir(), the os module is not there (at least not visible, usable). Is it gone?

Erik Aronesty
  • 11,620
  • 5
  • 64
  • 44
Quora Feans
  • 928
  • 3
  • 10
  • 21
  • 2
    `import os; del os; assert 'os' not in dir()` also holds in Python 2. –  Feb 07 '14 at 14:34
  • OK, that would be the wrong way of knowing whether the memory has been freed. – Quora Feans Feb 07 '14 at 14:36
  • 1
    Check `sys.modules`, not `dir`. – Wooble Feb 07 '14 at 14:39
  • 2
    @poke. I have already linked to that page. I am asking whether it's still uptodate. The answers there relate to Python 2.x, I asked about Python 3.x. – Quora Feans Feb 07 '14 at 17:54
  • @QuoraFeans Yeah, I got that link from you. The same situation still applies though. The module caching is by design. Also, in that question, the second answer refers to Python 3. – poke Feb 07 '14 at 17:55
  • @poke: but they explain how to re-load, not how to un-load (which is the bug in Python 2, and appears to be in Python 3 too). – Quora Feans Feb 07 '14 at 17:57
  • @QuoraFeans It’s not a bug. It’s *by design*. You can’t completely unload modules. – poke Feb 07 '14 at 17:57
  • 5
    @poke It's bad design and you're wrong: completely unloading pure-Python modules is [trivial](https://stackoverflow.com/a/487718/2809027). Completely unloading a top-level module `foo`, for example, reduces to `del sys.modules['foo']; del foo`. **That's it.** Completely unloading submodules is slightly more involved, but not really. Completely unloading C extensions, however, appears to be infeasible. – Cecil Curry Mar 11 '16 at 06:59
  • 1
    this is not a duplicate .... importlib has no "unload" function – Erik Aronesty Jul 25 '21 at 03:46

1 Answers1

0

The sys.modules does still hold a reference to the module.

>>> import six
>>> del six
>>> sys.modules["six"]
<module 'six' from '/usr/lib64/python3.3/site-packages/six.py'>

sys.modules still holds a reference. So I don't think you can unload a module in Python 3.3 either.

Keith
  • 42,110
  • 11
  • 57
  • 76
  • 12
    You _can_ [unload modules](https://stackoverflow.com/a/487718/2809027), but you didn't even really try. Since `six` is a top-level pure-Python module, unloading `six` reduces to **(A)** `del sys.modules['six']` and **(B)** `del six` (in either order). That's it. Deleting all references to that module results in that module being garbage collected. – Cecil Curry Mar 11 '16 at 07:02
  • @CecilCurry Why not make that an answer? – WestCoastProjects Jan 09 '23 at 04:13