Generatore pymongo fallisce - 'ritorno' con generatore di tesi all'interno
Domanda
Sto cercando di fare quanto segue:
def get_collection_iterator(collection_name, find={}, criteria=None):
collection = db[collection_name]
# prepare the list of values of collection
if collection is None:
logging.error('Mongo could not return the collecton - ' + collection_name)
return None
collection = collection.find(find, criteria)
for doc in collection:
yield doc
e chiamando come:
def get_collection():
criteria = {'unique_key': 0, '_id': 0}
for document in Mongo.get_collection_iterator('contract', {}, criteria):
print document
e vedo l'errore che dice:
File "/Users/Dev/Documents/work/dw/src/utilities/Mongo.py", line 96
yield doc
SyntaxError: 'return' with argument inside generator
che cosa è che sto facendo errato qui?
Soluzione
Sembra che il problema è che Python non permette di mixare return
e yield
-. Si utilizza sia all'interno get_collection_iterator
Chiarimento (grazie a Rob mayoff): return x
e yield
non può essere mescolato, ma una nuda return
possono
Altri suggerimenti
Your problem is in the event None
must be returned, but it is detected as a syntax error since the return would break the iteration loop.
Generators that are intended to use yield
to handoff values in loops can't use return with argument values, as this would trigger a StopIteration
error. Rather than returning None
, you may want to raise an exception and catch it in the calling context.
http://www.answermysearches.com/python-fixing-syntaxerror-return-with-argument-inside-generator/354/
def get_collection_iterator(collection_name, find={}, criteria=None):
collection = db[collection_name]
# prepare the list of values of collection
if collection is None:
err_msg = 'Mongo could not return the collecton - ' + collection_name
logging.error(err_msg)
raise Exception(err_msg)
collection = collection.find(find, criteria)
for doc in collection:
yield doc
You could make a special exception for this too if need be.