Unload a module in Python
Python does not support unloading modules.
However, unless your program loads an unlimited number of modules over time, that's not the source of your memory leak. Modules are normally loaded once at start up and that's it. Your memory leak most likely lies elsewhere.
In the unlikely case that your program really does load an unlimited number of modules over time, you should probably redesign your program. ;-)
I can not find an authoritative perspective on this in python3 (10 years later) (now python3.8
). However, we can do better percentage-wise now.
import gc
import sys
the_objs = gc.get_objects()
print(len(gc.get_objects())) # 5754 objects in memory
origin_modules = set(sys.modules.keys())
import http.client # it was renamed ;)
print(len(gc.get_objects())) # 9564 objects in memory
for new_mod in set(sys.modules.keys()) - origin_modules:
del sys.modules[new_mod]
try:
del globals()[new_mod]
except KeyError:
pass
try:
del locals()[new_mod]
except KeyError:
pass
del origin_modules
# importlib.invalidate_caches() happens to not do anything
gc.collect()
print(len(gc.get_objects())) # 6528 objects in memory
only increasing 13%. If you look at the kind of objects that get loaded in the new gc.get_objects
, some of them are builtins, source code, random.*
utilities, datetime
utilities, etc. I am mostly leaving this here as an update to start the conversation for @shuttle and will delete if we can make more progress.
I'm not sure about Python, but in other languages, calling the equivalent of gc.collect()
does not release unused memory - it will only release that memory if/when the memory is actually needed.
Otherwise, it makes sense for Python to keep the modules in memory for the time being, in case they need to be loaded again.