An Iterator Idiom

Moshe Zadka moshez at math.huji.ac.il
Mon May 3 16:36:13 EDT 1999


Hi!

I've seen the ``How do you do while(<>) in Python? We need assignment
in conditionals...No we don't...yes we do....while 1 is evil....is
not...'' thread once more, I decided to do something about it.

So here is my iterator class
--------------- cut here -------------
class iterator:
        def __init__(self, f, *args):
                self.f=f
                self.args=args
                self.i=0
        def __getitem__(self, i):
                if self.i<>i:
                        raise ValueError, 'items not accessed consecutively'
                val=apply(self.f, self.args)
                if not val:
                        raise IndexError, 'no more items'
                self.i=i+1
                return val
------------- cut here --------------------

How do I use it?

Well, something like

for line in iterator(sys.stdin.readline):
	sys.stdout.write(line)

as well as

for buff in iterator(sys.stdin.read, 1024):
	sys.stdout.write(buff)

Should work.

and-if-I-here-that-how-do-I-iterate-on-lines-question-one-more-time-I-swear-
someone-is-going-to-die-if-I-have-to-kill-my-self <0.9 wink>-ly y'rs, Z.

--
Moshe Zadka <mzadka at geocities.com>. 
QOTD: My own exit is more likely to be horizontal then perpendicular.






More information about the Python-list mailing list