Mailing List Archive

An Iterator Idiom
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@geocities.com>.
QOTD: My own exit is more likely to be horizontal then perpendicular.
An Iterator Idiom [ In reply to ]
Have you looked at the fileinput module? It seems to do much the same
thing.

Jeremy
An Iterator Idiom [ In reply to ]
Moshe Zadka <moshez@math.huji.ac.il> writes:

> 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.
>
[...]
>
> 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)

Nice -- but it has been done before, by several people. (Myself
included, if I am not mistaken). Check out dejanews. I think I called
it repeat. So:

for line in repeat(sys.stdin.readline):
process(line)

or something is what you should look for.

(I think it was even suggested as a built-in function.)

>
> Should work.

--

Magnus
Lie
Hetland http://arcadia.laiv.org <arcadia@laiv.org>