import atexit _Cleanup = [] def _clean(): global _Cleanup cleanlist = [ c for c in _Cleanup if c ] atexit.register(_clean) import fail