Skip to content

Instantly share code, notes, and snippets.

@shanemhansen
Created May 16, 2012 17:43
Show Gist options
  • Save shanemhansen/2712532 to your computer and use it in GitHub Desktop.
Save shanemhansen/2712532 to your computer and use it in GitHub Desktop.
Don't try this at home
import inspect
frames={}
class MyObj:
def __init__(self):
self.callbacks = []
def __del__(self):
print "callbacks"
for thing in self.callbacks:
try:
thing()
except Exception:
pass
def append(self, thingy):
self.callbacks.append(thingy)
def defer(thingy):
frame = inspect.stack()[1][0]
if '__atexit' not in frame.f_locals:
frame.f_locals['__atexit'] = MyObj()
frame.f_locals['__atexit'].append(thingy)
def foo():
f = open('/etc/hosts')
print "before defer"
defer (f.close)
print "after defer"
foo()
print "all callbacks should be called before this point"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment