In [13]:
class FakeDatabase(object):
    def __init__(self):
        self.open = False
    @property
    def isopen(self):
        return self.open
    def connect(self):
        assert not self.isopen, 'already open'
        self.open = True
        print 'Database opened'
    def close(self):
        assert self.isopen, 'already closed'
        self.open = False
        print 'Database closed'
    def execute(self, command):
        assert self.isopen, 'database not open'
        print 'Successfully executed %s' % command

In [15]:
d = FakeDatabase()
d.connect()
d.close()


Database opened
Database closed

In [18]:
from contextlib import contextmanager

@contextmanager
def connection():
    db = FakeDatabase()
    db.connect()
    yield db
    db.close()
    
with connection() as c:
    assert False
    c.execute('my command')


Database opened
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-18-d698be3777bb> in <module>()
      9 
     10 with connection() as c:
---> 11     assert False
     12     c.execute('my command')

AssertionError: 

In [20]:
@contextmanager
def safe_connection():
    db = FakeDatabase()
    try:
        db.connect()
        yield
    finally:
        db.close()
        
with safe_connection() as c:
    assert False
    c.execute('my command')


Database opened
Database closed
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-20-a070b95d9ae6> in <module>()
      9 
     10 with safe_connection() as c:
---> 11     assert False
     12     c.execute('my command')

AssertionError: