Skip to content

Instantly share code, notes, and snippets.

@lucaswiman
Last active December 23, 2015 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucaswiman/6709093 to your computer and use it in GitHub Desktop.
Save lucaswiman/6709093 to your computer and use it in GitHub Desktop.
Example of use of `contextlib.contextmanager`.
from time import sleep
def setup():
print 'setup'
def cleanup():
print 'cleanup'
from contextlib import contextmanager
@contextmanager
def manage_resource():
setup()
yield
cleanup()
with manage_resource():
sleep(5)
with manage_resource():
1/0 # Note that cleanup is not called when an exception is raised.
@contextmanager
def manage_resource_correctly():
setup()
try:
yield
finally:
cleanup()
with manage_resource_correctly():
sleep(5)
with manage_resource_correctly():
1/0 # Now cleanup is called in the finally block.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment