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

前端 未结 3 880
青春惊慌失措
青春惊慌失措 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:49

    You may create a iterator and set the flag as the instance property to iterator class as:

    class gen(object):
        def __init__(self, n):
            self.n = n
            self.num, self.nums = 0, []
            self.is_just_started = True  # Your flag
    
        def __iter__(self):
            return self
    
        # Python 3 compatibility
        def __next__(self):
            return self.next()
    
        def next(self):
            self.is_just_started = False  # Reset flag with next
            if self.num < self.n:
                cur, self.num = self.num, self.num+1
                return cur
            else:
                raise StopIteration()
    

    And your value check function would be like:

    def is_just_started(my_generator):
        return my_generator.is_just_started
    

    Sample run:

    >>> a = gen(2)
    
    >>> is_just_started(a)
    True
    
    >>> next(a)
    0
    >>> is_just_started(a)
    False
    
    >>> next(a)
    1
    >>> is_just_started(a)
    False
    
    >>> next(a)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 19, in next
    StopIteration
    

    To know the difference between iterator and generator, check Difference between Python's Generators and Iterators

提交回复
热议问题