2011-11-28 33 views
4

我尝试做以下与参数 '回归':pymongo发电机失效 - 内部发电机

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 

我在这做什么不正确?

+0

@MattFenwick是我没有挪亚 – daydreamer

回答

11

看来问题在于Python不允许你混合使用returnyield - 你在get_collection_iterator中都使用这两种。

澄清(感谢Rob mayoff):return xyield不能混用,而是裸露return可以

+4

你可以用'return'在发电机没有参数。你不能使用'return something'。 –

+0

@robmayoff - 良好的接收,谢谢! –

3

您的问题是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 

你可以做这个特殊的例外太多如果需要的话。