How to overide "for line in file:"
Harry George
harry.g.george at boeing.com
Mon Feb 23 02:41:52 EST 2004
Shalabh Chaturvedi <shalabh at cafepy.com> writes:
> David Morgenthaler wrote:
>
> > How does one overide the iterator implied by the construct "for line
> > in file:"?
> >
>
> 'for' uses __iter__().
>
> Subclass file and redefine __iter__(self). It should return an object that
> has the next() method which returns the next item, or raises StopIteration
> if finished. Returning self from __iter__() is ok (then you can put the
> next() in the same class).
>
> An easier alternative is to make __iter__() a generator function (so calling
> it automatically returns a 'generator' object, which has next() on it, and
> also raises StopIteration when done).
>
> HTH,
> Shalabh
Slightly off topic, how do you "reset" or backup an iter? Someone
asked me a couple of days ago how to use yield and then backup if the
yielded line failed to meet certain criteria. Essentailly a
lookahead(1) situation.
Historically, I've made a list, kept track of the line index, and
decremented that when I needed to backup. Does iter have something
equiv?
--
harry.g.george at boeing.com
6-6M21 BCA CompArch Design Engineering
Phone: (425) 342-0007
More information about the Python-list
mailing list