Last active
October 4, 2015 23:01
-
-
Save poros/e4c7310195e007700285 to your computer and use it in GitHub Desktop.
Define a context manager class
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
class DBConnection(object): | |
def __init__(self, address): | |
self.crappy_db = CrappyDBConnection(address) | |
def __enter__(self): | |
self.crappy_db.connect() | |
return self # what is returned here will be availabe via "as" | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if exc_type == ConnectionError: | |
logging.exception('Connection dropped') | |
self.crappy_db.cleanup('rollback') | |
else: | |
self.crappy_db.cleanup('commit') | |
self.creappy_db.disconnect() | |
def more_awesome_methods(self): | |
... | |
# THIS | |
with DBConnection('127.0.0.1') as db: | |
... | |
# INSTEAD OF | |
db = CrappyDBConnection('127.0.0.1') | |
try: | |
db.connect() | |
... | |
except ConnectionError: | |
logging.exception('Connection dropped') | |
db.cleanup('rollback') | |
else: | |
db.cleanup('commit') | |
finally: | |
db.disconnect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment