Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 877119
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T11:33:12+00:00 2026-05-15T11:33:12+00:00

TL/DR: import gc, sys print len(gc.get_objects()) # 4073 objects in memory # Attempt to

  • 0

TL/DR:

import gc, sys

print len(gc.get_objects()) # 4073 objects in memory

# Attempt to unload the module

import httplib
del sys.modules["httplib"]
httplib = None

gc.collect()
print len(gc.get_objects()) # 6745 objects in memory

UPDATE
I’ve contacted Python developers about this problem and indeed it’s not going to be possible to unload a module completely “in next five years”. (see the link)

Please accept that Python indeed does not support unloading modules for severe, fundamental, insurmountable, technical problems, in 2.x.


During my recent hunt for a memleak in my app, I’ve narrowed it down to modules, namely my inability to garbage collect an unloaded module. Using any method listed below to unload a module leaves thousands of objects in memory. In other words – I can’t unload a module in Python…

The rest of the question is attempt to garbage collect a module somehow.

Let’s try:

import gc
import sys

sm = sys.modules.copy()  # httplib, which we'll try to unload isn't yet 
                         # in sys.modules, so, this isn't the source of problem

print len(gc.get_objects()) # 4074 objects in memory

Let’s save a copy of sys.modules to attempt to restore it later.
So, this is a baseline 4074 objects. We should ideally return to this somehow.

Let’s import a module:

import httplib
print len(gc.get_objects()) # 7063 objects in memory

We’re up to 7K non-garbage objects.
Let’s try removing httplib from sys.modules.

sys.modules.pop('httplib')
gc.collect()
print len(gc.get_objects()) # 7063 objects in memory

Well, that didn’t work. Hmm, but isn’t there a reference in __main__? Oh, yeah:

del httplib
gc.collect()
print len(gc.get_objects()) # 6746 objects in memory

Hooray, down 300 objects. Still, no cigar, that’s way more than 4000 original objects.
Let’s try restoring sys.modules from copy.

sys.modules = sm
gc.collect()
print len(gc.get_objects()) # 6746 objects in memory

Hmmm, well that was pointless, no change..
Maybe if we wipe out globals…

globals().clear()
import gc # we need this since gc was in globals() too
gc.collect()
print len(gc.get_objects()) # 6746 objects in memory

locals?

locals().clear()
import gc # we need this since gc was in globals() too
gc.collect()
print len(gc.get_objects()) # 6746 objects in memory

What the.. what if we imported a module inside of exec?

local_dict = {}
exec 'import httplib' in local_dict
del local_dict
gc.collect()
print len(gc.get_objects())  # back to 7063 objects in memory

Now, that’s not fair, it imported it into __main__, why? It should have never left the local_dict… Argh! We back to fully imported httplib.
Maybe if we replaced it with a dummy object?

from types import ModuleType
import sys
print len(gc.get_objects())  # 7064 objects in memory

Bloody…..!!

sys.modules['httplib'] = ModuleType('httplib')
print len(gc.get_objects())  # 7066 objects in memory

Die modules, die!!

import httplib
for attr in dir(httplib):
    setattr(httplib, attr, None)
gc.collect()
print len(gc.get_objects())  # 6749 objects in memory

Okay, after all attempts, the best is +2675 (nearly +50%) from starting point… That’s just from one module… That doesn’t even have anything big inside…

Ok, now seriously, where’s my error?
How do I unload a module and wipe out all of it’s contents?
Or is Python’s modules one giant memory leak?

Full source in simpler to copy form: http://gist.github.com/450606

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T11:33:13+00:00Added an answer on May 15, 2026 at 11:33 am

    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. 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

import socket, sys, string if len(sys.argv) !=4 : print Usage: ./supabot.py <host> <port> <channel>
in py_script.py: import os import sys l = len(sys.argv) if l == 1: print
import sys def checkarg(): try: filename=str(sys.argv[1]) if filename==-mycommand: print SPECIFIC_TEXT sys.exit() else: return filename
import sys, os X = os.system(ipconfig) print X 0 I know its simple, I'm
This Python: data = {} def f(): pass import sys help(sys.modules[__name__]) Prints this: Help
import sys sys.path.append('/home/myuser/svn-repos/myproject') from myproject.settings import * But, it says module not found when
from sys import argv from os.path import exists script, from_file, to_file = argv print
from sys import exit from random import randint class Map(object): def death(): print quips[randint
import sys final_set = [] init_set = [] for i in range(1,len(sys.argv)): init_set.append(sys.argv[i]) for
import MySQLdb import sys from libdesklets.controls import Control from IDBConnection import IDBConnection class DBConnection(Control,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.