Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Created August 6, 2014 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drgarcia1986/2fbf98f0a7fdacf995fe to your computer and use it in GitHub Desktop.
Save drgarcia1986/2fbf98f0a7fdacf995fe to your computer and use it in GitHub Desktop.
def delete_module(modname, paranoid=None):
from sys import modules
try:
thismod = modules[modname]
except KeyError:
raise ValueError(modname)
these_symbols = dir(thismod)
if paranoid:
try:
paranoid[:] # sequence support
except:
raise ValueError('must supply a finite list for paranoid')
else:
these_symbols = paranoid[:]
del modules[modname]
for mod in modules.values():
try:
delattr(mod, modname)
except AttributeError:
pass
if paranoid:
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
continue
try:
delattr(mod, symbol)
except AttributeError:
pass
'''
>>> import sys
>>> import pymongo
>>> 'pymongo' in sys.modules.keys()
True
>>> delete_module('pymongo')
>>> 'pymongo' in sys.modules.keys()
False
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment