我试图在python 2.6中定义类似下面的生成器:
def getGenerator(self, keyIterator):
def bufferFullCallback(list_of_keys):
some_values = api_call(list_of_keys)
for value in some_values:
yield value # I want this value to be yielded by getGenerator
for key in keyIterator:
with MyBuffer(self.buffer_size, bufferFullCallback) as buf:
buf.addToBuffer(key)
在这里,当缓冲区已满时,我得到一个回调,其中我进行一些API调用以获得与键对应的一堆值。现在,我需要'getGenerator'来产生它在回调函数中接收的值。但是,如果我在回调中产生值,那么该回调基本上变成了一个生成器;这显然是错误的做法。你能否在回调中建议正确的方法来产生价值,或者甚至是可能有帮助的不同重构?
答案 0 :(得分:1)
这样的事情:
def getGenerator(self, keyIterator):
results = []
def bufferFullCallback(list_of_keys):
results.extend(api_call(list_of_keys))
for key in keyIterator:
with MyBuffer(self.buffer_size, bufferFullCallback) as buf:
buf.addToBuffer(key)
for value in results:
yield value