在生成器函数中,我怎样才能知道它是否已经产生了任何东西?
def my_generator(stuff):
# complex logic that interprets stuff and may or may not yield anything
# I only want to yield this if nothing has been yielded yet.
yield 'Nothing could be done with the input.'
您需要自己保留一个标志,或在顶部重构代码。如果事情太复杂,听起来你的函数可能做的太多了。
此外,如果这是您的信息,听起来您可能想要一个例外。
跟踪自己的一种简单方法是将复杂的逻辑包装到内部生成器中。
这样做的好处是,它不需要对复杂的逻辑进行任何更改。
def my_generator(stuff):
def inner_generator():
# complex logic that interprets stuff and may or may not yield anything
if stuff:
yield 11 * stuff
# I only want to yield this if nothing has been yielded yet.
have_yielded = False
for x in inner_generator():
have_yielded = True
yield x
if not have_yielded:
yield 'Nothing could be done with the input.'
测试#1:
print(list(my_generator(1)))
=>
[11]
测试#2:
print(list(my_generator(None)))
=>
['Nothing could be done with the input.']
- - 替代 - -
更复杂的代码,那可能是过早的优化。避免重复将 have_yielded 设置为 True。仅当您的生成器从不产生“无”作为其第一个值时才有效:
...
# I only want to yield this if nothing has been yielded yet.
have_yielded = False
g = inner_generator()
x = next(g, None)
if x is not None:
yield x
have_yielded = True
for x in g:
yield x
if not have_yielded:
yield 'Nothing could be done with the input.'