0

デバッグしようとしている次のメソッドがあります。私の問題は、main から insertNewDataInDatabase() メソッドを呼び出すと、メソッドの for ループの先頭に移動しますが、データベース実行ステートメントをスキップしてすぐに getInStockItems() メソッドに移動することです。私はすでにそのメソッドを呼び出しており、insertNewDataInDatabase はそれを呼び出していないためです。

問題に関係がある場合、データセットはジェネレーターオブジェクトです。

どんな助けでも大歓迎です!

def deleteOldDataFromDatabase(company, c):
    c.execute('DELETE FROM company WHERE Company=?',(company,))


def insertNewDataInDatabase(items, c):
    for each in items:
        c.execute('INSERT INTO ammo VALUES (?, ?, ?, ?, ?, ?)', ("NULL", each["Company"], each["Value"],
                                                             each["Product"], each["Price"], each["Url"]))
def getInStockItems(c):
    for i in chain(ctd.main()):
        deleteOldDataFromDatabase(i[1], c)
        for each in i[0]:
            yield each

def retrieveDatafromDB(c):
    c.execute("SELECT * from company")
    return c.fetchall()

def main():
    with sqlite3.connect(database) as connection:
        c = connection.cursor()
        dataset = getInStockItems(c)
        insertNewDataInDatabase(dataset, c)
        return retrieveDatafromDB(c)

if __name__ == '__main__':
    main()
4

1 に答える 1

3

This is expected behaviour. getInStockItems() is a generator function, and the body of a generator function is not executed until you iterate over the generator.

From the yield expressions documentation:

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to generator’s caller.

The line dataset = getInStockItems(c) creates that generator. You pass the generator to insertNewDataInDatabase() and the for loop starts iterating over the generator. Iteration means the generator.next() method is called, advancing the generator function.

So, until for each in items: starts executing, getInStockItems() does nothing at all. Calling .next() on the generator starts running that function, until the yield statement returns the first i[0] expression to the for loop, at which point it the generator function is suspended again.

于 2013-06-15T16:46:27.683 に答える