Last active
June 13, 2017 19:29
-
-
Save Jwely/032f021aafdce0d9402713864306e57a to your computer and use it in GitHub Desktop.
context manager demo
This file contains hidden or 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 contextlib import contextmanager | |
@contextmanager | |
def manage_something(something): | |
""" this is the general structure of a contextmanager """ | |
try: | |
# prepare the something | |
yield something | |
except Exception as e: | |
# do something when an error occurs, such as rollback some changes or close a connection | |
# now raise the exception that caused the error (or maybe handle it instead!) | |
raise e | |
finally: | |
# finalize something, such as close a connection or commit some database changes | |
pass | |
if __name__ == "__main__": | |
with manage_something(my_something) as this_thing: | |
# do some stuff | |
this_thing.foo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment