使用SQLAlchemy连接到MySQL,我已经厌倦了写这样的东西:
with closing(engine) as connection:
do_sql_stuff(connection)此模式在我的代码的许多区域中重复出现,而且随着__del__的出现,这似乎不再是必要的。为什么不实现一个类来包装连接的创建和关闭:
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()这仅仅是两种不同的风格/偏好,还是有更重要的原因表明使用with closing()比使用__del__更好(反之亦然)?
发布于 2012-05-27 00:26:53
不能保证何时实际调用__del__ (或者在循环引用的情况下是否调用它)。with closing(...) as ...:保证每当您退出with子句时都会调用清理代码。
https://stackoverflow.com/questions/10767905
复制相似问题