public
Created

  • Download Gist
The hunt for Pythons memory leaks.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import gc
import sys
 
sm = sys.modules.copy()
print len(gc.get_objects()) # 4075
 
import httplib
print len(gc.get_objects()) # 7064
 
sys.modules.pop('httplib')
gc.collect()
print len(gc.get_objects()) # 7064
 
del httplib
gc.collect()
print len(gc.get_objects()) # 6747
 
sys.modules = sm
gc.collect()
print len(gc.get_objects()) # 6747
 
globals().clear()
import gc
gc.collect()
print len(gc.get_objects()) # 6747
 
locals().clear()
import gc
gc.collect()
print len(gc.get_objects()) # 6747
 
g = {}
exec 'import httplib' in g
del g
gc.collect()
print len(gc.get_objects()) # back to 7064
 
from types import ModuleType
import sys
print len(gc.get_objects()) # 7064
sys.modules['httplib'] = ModuleType('httplib')
print len(gc.get_objects()) # 7066
 
for key in sys.modules.keys():
del sys.modules[key]
gc.collect()
print len(gc.get_objects()) # 7064
import httplib
for attr in dir(httplib):
setattr(httplib, attr, None)
gc.collect()
print len(gc.get_objects()) # 6749

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.