简体   繁体   中英

pymongo generator fails - 'return' with argument inside 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 calling like :

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

and I see the error saying :

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

what is that I am doing incorrect here?

It seems the problem is that Python doesn't allow you to mix return and yield -- you use both within get_collection_iterator .

Clarification (thanks to rob mayoff): return x and yield can't be mixed, but a bare return can

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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