简体   繁体   English

pymongo生成器失败 - 在发生器内使用参数'返回'

[英]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 . 似乎问题是Python不允许你混合returnyield - 你在get_collection_iterator使用它们。

Clarification (thanks to rob mayoff): return x and yield can't be mixed, but a bare return can 澄清(感谢rob mayoff): return x并且yield不能混合,但是return可以

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. 你的问题是在必须返回None下,但它被检测为语法错误,因为返回会破坏迭代循环。

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. 旨在使用yield来循环切换值的生成器不能使用带参数值的return,因为这会触发StopIteration错误。 Rather than returning None , you may want to raise an exception and catch it in the calling context. 您可能希望引发异常并在调用上下文中捕获它,而不是返回None

http://www.answermysearches.com/python-fixing-syntaxerror-return-with-argument-inside-generator/354/ 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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