Last active
December 23, 2015 23:19
-
-
Save lucaswiman/6709093 to your computer and use it in GitHub Desktop.
Example of use of `contextlib.contextmanager`.
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
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