ActiveState Code

Recipe 438479: Auto Incrementer an Example of __call__ and yield


This will automaticly return then next integer forever it starts with 0. This is an example of how to make a generator and how to make a callable object.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Inc:
    def __init__(self):
        self.x=0
        self.inc=self.giveone()
    def giveone(self):
        while True:
            yield self.x
            self.x+=1
    def __call__(self):
        return self.inc.next()  
inc=Inc()

for x in range(10):
    inc()
    
assert (inc()==10)==True
assert (inc()==12)==False

Discussion

I made this because I was making animated gifs. I wanted to name all the pictures in sequence and this was a nice clean way to generate the next number in the sequence. I did not need to backtrack at all so it seemed like a generator was called for. Also I did not want to call gen.next() in order to get my number.

Comments

  1. 1. At 9:13 a.m. on 26 jul 2005, Georg Brandl said:

    Easier... You don't benefit from using a class here.

    def inc(x=0): while 1: yield x x += 1

    is certainly simpler.

  2. 2. At 9:41 a.m. on 26 jul 2005, Radek Kanovsky said:

    Batteries Included.

    >>> import itertools
    >>> inc = itertools.count(0).next
    >>> inc()
    0
    >>> inc()
    1
    >>> inc()
    2
    
  3. 3. At 11:03 a.m. on 29 jul 2005, Chad Crabtree (the author) said:

    This is what I should have used. I obviously should look more closely at itertools.

Sign in to comment