How can I tell whether a generator was just-started?

前端 未结 3 882
青春惊慌失措
青春惊慌失措 2020-12-28 12:49

I\'d like a function, is_just_started, which behaves like the following:

>>> def gen(): yield 0; yield 1
>>> a = gen()
>>         


        
3条回答
  •  既然无缘
    2020-12-28 13:26

    Make a new generator which simply yields from your generator of interest. It sets a flag once the first value has been consumed. Afterwards, it can simply use yield from for the rest of the items.

    Use the substitute generator as a drop in replacement for the generator you're interested in monitoring the "is_just_started" state.

    This technique is non-intrusive, and can be used even on generators for which you have no control over the source code.

提交回复
热议问题