best way to run python generator cleanup code

后端 未结 3 703
鱼传尺愫
鱼传尺愫 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 00:47

    You can use a context manager and the with statement. contextlib provides 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
    

    This will automatically call close() on dbc at the end of the with block, even if an exception has been raised.

提交回复
热议问题