[英]Python 2.7: “Has anything been yielded?”
Within a generator function, how can I find out if it has yielded anything yet? 在生成器函数中,如何确定它是否产生了任何结果?
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.'
You'd need to keep a flag yourself, or restructure the code at the top. 您需要自己保留一个标志,或在顶部重组代码。 If things are too complex, it sounds like your function might do too much.
如果事情太复杂,听起来您的函数可能做得太多。
Also, if that's your message, it sounds like you may want an exception instead. 另外,如果这是您的消息,听起来您可能想要例外。
A simple way to keep track yourself, is to wrap the complex logic into an inner generator. 跟踪自己的一种简单方法是将复杂的逻辑包装到内部生成器中。
What's great about this, is it does not require any change to that complex logic. 这样做的好处是,它不需要对复杂的逻辑进行任何更改。
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.'
Test #1: 测试#1:
print(list(my_generator(1)))
=> =>
[11]
Test #2: 测试2:
print(list(my_generator(None)))
=> =>
['Nothing could be done with the input.']
--- An Alternative --- - - 替代 - -
More complicated code, that is probably a premature optimization. 更复杂的代码,可能是过早的优化。 Avoids repeatedly setting have_yielded to True.
避免重复将have_yielded设置为True。 Only works if your generator never produces "None" as its first value:
仅当生成器从不产生“ None”作为第一个值时才起作用:
...
# 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.'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.