如何编写永不产生任何结果的Python生成器函数 [英] How to write Python generator function that never yields anything
问题描述
我想编写一个Python生成器函数,该函数实际上从不产生任何结果.基本上,这是一个什么都不做"的插件,可以由希望调用生成器的其他代码使用(但并不总是需要它的结果).到目前为止,我有这个:
I want to write a Python generator function that never actually yields anything. Basically it's a "do-nothing" drop-in that can be used by other code which expects to call a generator (but doesn't always need results from it). So far I have this:
def empty_generator():
# ... do some stuff, but don't yield anything
if False:
yield
现在,这可以正常工作,但是我想知道是否还有一种更富有表现力的方式来表达同一件事,也就是说,即使函数从不产生任何值,也将其声明为生成器.我上面采用的技巧是向Python显示函数中的yield语句,即使它无法访问.
Now, this works OK, but I'm wondering if there's a more expressive way to say the same thing, that is, declare a function to be a generator even if it never yields any value. The trick I've employed above is to show Python a yield statement inside my function, even though it is unreachable.
推荐答案
另一种方法是
def empty_generator():
return
yield
并不是真正的更具表现力",而是更短. :)
Not really "more expressive", but shorter. :)
请注意,iter([])
或简称为[]
也可以.
Note that iter([])
or simply []
will do as well.
这篇关于如何编写永不产生任何结果的Python生成器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!