문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top