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?

9
  • 2
    import os; del os; assert 'os' not in dir() also holds in Python 2. Commented Feb 7, 2014 at 14:34
  • 1
    Check sys.modules, not dir. Commented Feb 7, 2014 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. Commented Feb 7, 2014 at 17:54
  • 5
    @poke It's bad design and you're wrong: completely unloading pure-Python modules is trivial. 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. Commented Mar 11, 2016 at 6:59
  • 1
    this is not a duplicate .... importlib has no "unload" function Commented Jul 25, 2021 at 3:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You can unload modules, 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.
@CecilCurry Why not make that an answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.