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
我在这里做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题似乎在于 Python 不允许您混合使用 return 和yield——您可以在 get_collection_iterator 中使用两者。
澄清(感谢 rob Mayoff):
return x
和yield
不能混合使用,但裸露的return
可以It seems the problem is that Python doesn't allow you to mix
return
andyield
-- you use both withinget_collection_iterator
.Clarification (thanks to rob mayoff):
return x
andyield
can't be mixed, but a barereturn
can您的问题在于必须返回
None
事件,但它被检测为语法错误,因为返回会破坏迭代循环。打算使用
yield
在循环中传递值的生成器不能将 return 与参数值一起使用,因为这会触发StopIteration
错误。您可能希望引发异常并在调用上下文中捕获它,而不是返回None
。http://www.answermysearches.com/ python-fixing-syntaxerror-return-with-argument-inside-generator/354/
如果需要的话,您也可以为此制定一个特殊的例外。
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 aStopIteration
error. Rather than returningNone
, 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/
You could make a special exception for this too if need be.