How to write Python generator function that never yields anything

老子叫甜甜 提交于 2020-07-17 09:29:06

问题


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

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.


回答1:


Another way is

def empty_generator():
    return
    yield

Not really "more expressive", but shorter. :)

Note that iter([]) or simply [] will do as well.




回答2:


An even shorter solution:

def empty_generator():
  yield from []



回答3:


Edit:

This doesn't work- read comments


can't you just yield None? Seems like it would be easier to read to me.



来源:https://stackoverflow.com/questions/6266561/how-to-write-python-generator-function-that-never-yields-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!