运行python生成器清理代码的最佳方法

时间:2013-10-16 18:53:07

标签: python generator mysql-python

我正在尝试编写一个生成器函数,该函数从数据库中获取行并一次返回一个。但是,我不确定下面标记**的清理代码是否按照我的想法执行。如果没有,那么将清理代码放在最后一个yield语句之后执行的生成器本身的最佳方法是什么?我看着捕获StopIteration,但这似乎是从调用者完成的,而不是在生成器中。

def MYSQLSelectGenerator(stmt):
...
try:   
    myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
    dbc=myDB.cursor()
    dbc.execute(stmt)
    d = "asdf"
    while d is not None:
        d = dbc.fetchone() #can also use fetchmany() to be more efficient
        yield d
    dbc.close() #** DOES THIS WORK AS I INTEND, MEANING AS SOON AS d = "None"
except MySQLdb.Error, msg:
    print("MYSQL ERROR!")
    print msg

3 个答案:

答案 0 :(得分:3)

您的版本会在dbc.close()后立即运行d is None,但如果引发异常则不会。你需要一个finally clause。即使引发异常,此版本也保证运行dbc.close()

try:   
    myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
    dbc = myDB.cursor()
    dbc.execute(stmt)
    d = "asdf"
    while d is not None:
        d = dbc.fetchone() #can also use fetchmany() to be more efficient
        yield d
except MySQLdb.Error, msg:
    print("MYSQL ERROR!")
    print msg
finally:
    dbc.close()

答案 1 :(得分:3)

您可以做的一件事是使用finally子句。另一种选择(在这里可能有些过分但是有用的东西要知道)是创建一个与with语句一起使用的类:

class DatabaseConnection:
    def __init__(self, statement):
        self.statemet = statement
    def __enter__(self): 
        self.myDB = MySQLdb.connect(host=..., port=...,user=...,passwd=...,db=...)
        self.dbc = myDB.cursor()
        self.dbc.execute(self.statement)
        self.d = "asdf"
    def __exit__(self, exc_type, exc_value, traceback):
        self.dbc.close()

    def __iter__(self):
        while self.d is not None:
            self.d = self.dbc.fetchone()
            yield self.d


with DatabaseConnection(stmnt) as dbconnection:
    for i in dbconnection:
        print(i)

答案 2 :(得分:1)

您可以使用上下文管理器和with语句。 contextlib提供closing

from contextlib import closing

myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)   
with closing(myDB.cursor()) as dbc:
    dbc.execute(stmt)
    d = "asdf"
    while d is not None:
        d = dbc.fetchone() #can also use fetchmany() to be more efficient
        yield d

这将在close()块的末尾自动调用dbc上的with,即使已经引发了异常。