blaze
blaze

Reputation: 2668

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. 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

Upvotes: 0

Views: 2749

Answers (1)

agf
agf

Reputation: 176800

First of all, remove return, it's not necessary.

Your problem isn't with test() but how you're calling it. Don't just call 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

Upvotes: 2

Related Questions