Wednesday, December 8, 2010

self destructing module

#self_destruct.py
def self_destruct():
   import sys
   for k,m in sys.modules.items():
      if getattr(m, "__file__", None) is __file__:
         print "removing self from sys.modules:", repr(k)
         del sys.modules[k]

>>> import self_destruct
>>> reload(self_destruct)
<module 'self_destruct' from 'self_destruct.pyc'>
>>> self_destruct.self_destruct()
removing self from sys.modules: 'self_destruct'
>>> reload(self_destruct)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: reload(): module self_destruct not in sys.modules

No comments:

Post a Comment