Using SQLAlchemy to connect to MySQL and I’ve gotten tired of writing things like this:
with closing(engine) as connection:
do_sql_stuff(connection)
This pattern is repeated throughout many areas of my code and it seems with the availability of __del__ this is not necessary. Why not just implement a class to wrap the connection creation and closing:
class MyConnectionManager(object):
def __init__(self, db_uri):
self.__db_engine = sqlalchemy.create_engine(db_uri)
self.__db_conn = self.__db_engine.connect()
def __del__(self):
self.__db_conn.close()
Is this simply two different styles/preferences, or are there more important reasons that using with closing() is a better way to go that using __del__ (or vice versa)?
There is no guarantee about when
__del__is actually called (or if it is called at all in the case of circular references).with closing(...) as ...:guarantees that the cleanup code is called whenever you exit thewithclause.