Last active
October 4, 2015 23:02
-
-
Save poros/f66e6166dbf593bf4980 to your computer and use it in GitHub Desktop.
Define a context manager generator
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 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