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
First of all, remove
return, it’s not necessary.Your problem isn’t with
test()but how you’re calling it. Don’t just calltest().Do something like:
And you’ll get one item at a time. What this is doing is basically: