I'm using SqlAlchemy core to access my database. I'm just wondering if there's a specific reason why the
ResultProxy class doesn't implement the
__enter__ and
__exit__ methods for automatically closing the results of a query using Python's
with statement. This would make the following code possible
stmt = select(mytable)
with engine.execute(stmt) as result:
# do something with result...
pass
#result (and possibly connection) gets automatically closed
For now, I'm helping myself with a AutoClose class:
def __init__(self, close_object):
self.close_object = close_object
def __exit__(self, type, value, traceback):
self.close_object.close()
which allows me to do something like
stmt = select(mytable)
with AutoClose(engine.execute(stmt)) as result:
# do something with result...
pass
#result (and possibly connection) gets automatically closed
But I must admit I see no reason why the with-Protocol shouldn't be implemented in ResultProxy itself.