我正在尝试执行以下操作:

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 

并打电话:

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

我看到错误说:

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

我在这里做什么不正确?

有帮助吗?

解决方案

似乎问题是Python不允许您混合 returnyield - 您在内部使用两者 get_collection_iterator.

澄清(感谢Rob Mayoff): return xyield 不能混杂,但是裸露 return 能够

其他提示

您的问题是 None 必须返回,但是将其视为语法错误,因为返回会破坏迭代循环。

打算使用的发电机 yield 循环中的交接值不能将返回与参数值一起使用,因为这会触发一个 StopIteration 错误。而不是返回 None, ,您可能需要提出一个例外,并在呼叫上下文中捕获它。

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 

如果需要,您也可以为此做一个特殊的例外。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top