Skip to content

Instantly share code, notes, and snippets.

@lfranchi
Created October 31, 2012 15:18
Show Gist options
  • Save lfranchi/3987604 to your computer and use it in GitHub Desktop.
Save lfranchi/3987604 to your computer and use it in GitHub Desktop.
>>> from contextlib import contextmanager
>>> @contextmanager
... def foobar(baz):
... print "Before"
... yield
... print "After"
...
>>> with foobar(0):
... print "Doing stuff"
... raise Exception
... print "Done stuff"
...
Before
Doing stuff
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
Exception
>>>
@lfranchi
Copy link
Author

In [12]: class Foo(object):
....: def init(self): pass
....: def enter(self): print "ENTER"
....: def exit(self, type, value, traceback): print "EXIT"

In [17]: with Foo():
print "hiiii"
raise Exception
....: print "BYE"
....:
ENTER
hiiii
EXIT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment