best way to run python generator cleanup code

后端 未结 3 739
鱼传尺愫
鱼传尺愫 2021-01-14 00:41

I\'m trying to write a generator function that gets rows out of a database and returns them one at a time. However, I\'m not sure if the cleanup code marked ** below execute

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 01:11

    One thing you could do is use a finally clause. Another option (that may be overkill here but is a useful thing to know about) is to make a class that works with the with statement:

    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)
    

提交回复
热议问题