简体   繁体   English

带 pymongo 的发电机 function

[英]Generator function with pymongo

I am trying to make a generator function that yields an item on each call, however I keep getting the same item.我正在尝试制作一个生成器 function ,它在每次调用时都会产生一个项目,但是我一直得到相同的项目。 Here is my code:这是我的代码:

  1 from pymongo import Connection
  2 
  3 connection = Connection()
  4 db = connection.store
  5 collection = db.products
  6 
  7 def test():
  8         global collection #using a global variable just for the test.
  9         items = collection.find()
  10        for item in items:
  11                 yield item['description']
  12        return

First of all, remove return , it's not necessary.首先,删除return ,没有必要。

Your problem isn't with test() but how you're calling it.您的问题不在于test()而是您如何称呼它。 Don't just call test() .不要只调用test()

Do something like:执行以下操作:

for item in test():
    print item

And you'll get one item at a time.而且您一次只能得到一件。 What this is doing is basically:这基本上是:

from exceptions import StopIteration
it = iter(test())

while True:
    try:
        item = it.next()
    except StopIteration:
        break
    print item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM