2011-11-28 71 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 

你可以做這個特殊的例外太多如果需要的話。