Created
May 16, 2012 17:43
-
-
Save shanemhansen/2712532 to your computer and use it in GitHub Desktop.
Don't try this at home
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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