Simpler way to run a generator function without caring about items

前端 未结 4 1249
温柔的废话
温柔的废话 2020-12-17 17:20

I have some use cases in which I need to run generator functions without caring about the yielded items.
I cannot make them non-generaor functions because in other use c

4条回答
  •  遥遥无期
    2020-12-17 17:41

    One very simple and possibly efficient solution could be

    def exhaust(generator): all(generator)
    

    if we can assume that generator will always return True (as in your case where a tuple of 2 elements (success,table) is true even if success and table both are False), or: any(generator) if it will always return False, and in the "worst case", all(x or True for x in generator).

    Being that short & simple, you might not even need a function for it!

    Regarding the "why?" comment (I dislike these...): There are many cases where one may want to exhaust a generator. To cite just one, it's a way of doing a for loop as an expression, e.g., any(print(i,x) for i,x in enumerate(S)) - of course there are less trivial examples.

提交回复
热议问题