Welcome, guest | Sign In | My Account | Store | Cart

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, 17 lines
 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

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.

3 comments

Georg Brandl 18 years, 9 months ago  # | flag

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

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

is certainly simpler.

Radek Kanovsky 18 years, 9 months ago  # | flag

Batteries Included.

>>> import itertools
>>> inc = itertools.count(0).next
>>> inc()
0
>>> inc()
1
>>> inc()
2
Chad Crabtree (author) 18 years, 9 months ago  # | flag

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

Created by Chad Crabtree on Tue, 26 Jul 2005 (PSF)
Python recipes (4591)
Chad Crabtree's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks