Skip to content

Instantly share code, notes, and snippets.

@poros
Last active October 4, 2015 23:02
Show Gist options
  • Save poros/f66e6166dbf593bf4980 to your computer and use it in GitHub Desktop.
Save poros/f66e6166dbf593bf4980 to your computer and use it in GitHub Desktop.
Define a context manager generator
from contextlib import contextmanager
@contextmanager
def connect_to_db(address):
db = CrappyDBConnection(address)
try:
yield db
except ConnectionError:
logging.exception('Connection dropped')
db.cleanup('rollback')
else:
db.cleanup('commit')
db.disconnect()
# USE LIKE
with connect_to_db(address) as db:
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment