[英]Return value in generator function Python 2
I'm wondering how I can write a generator function that also has the option to return a value. 我想知道如何编写一个生成器函数,该函数还可以选择返回值。 In Python 2, you get the following error message if a generator function tries to return a value. 在Python 2中,如果生成器函数尝试返回值,则会收到以下错误消息。 SyntaxError: 'return' with argument inside generator
Is it possible to write a function where I specify if I want to receive a generator or not? 是否可以在我指定是否要接收生成器的地方编写函数?
For example: 例如:
def f(generator=False):
if generator:
yield 3
else:
return 3
Mandatory reading: Understanding Generators in Python 必读: 了解Python中的生成器
Key information: 关键信息:
yield
anywhere in a function makes it a generator. 函数中任何地方的yield
使其成为生成器。
Function is marked as generator when code is parsed. 解析代码时,功能被标记为生成器。 Therefore, it's impossible to toggle function behavior (generator / not generator) based on argument passed in runtime. 因此,不可能根据运行时传递的参数来切换函数行为(生成器/非生成器)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.