The pymongo generator does not work - "return" with an argument inside the generator

I am trying to do the following:

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 

and caller:

 def get_collection(): criteria = {'unique_key': 0, '_id': 0} for document in Mongo.get_collection_iterator('contract', {}, criteria): print document 

and I see an error:

 File "/Users/Dev/Documents/work/dw/src/utilities/Mongo.py", line 96 yield doc SyntaxError: 'return' with argument inside generator 

what am i doing wrong here?

+4
source share
2 answers

The problem seems to be that Python does not allow you to mix return and yield - you are using both get_collection_iterator .

Clarification (thanks to roboff): return x and yield cannot be mixed, but bare return can

+11
source

Your problem is that the None event should be returned, but it is detected as a syntax error, since the return interrupts the iteration loop.

Generators designed to use yield for transfer values ​​in loops cannot use return with argument values, as this will cause a StopIteration error. Instead of returning None you can throw 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 can make a special exception for this if necessary.

+3
source

Source: https://habr.com/ru/post/1383530/


All Articles