Skip to content

Instantly share code, notes, and snippets.

@Jwely
Last active June 13, 2017 19:29
Show Gist options
  • Save Jwely/032f021aafdce0d9402713864306e57a to your computer and use it in GitHub Desktop.
Save Jwely/032f021aafdce0d9402713864306e57a to your computer and use it in GitHub Desktop.
context manager demo
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