[Python-Dev] Single- vs. Multi-pass iterability

Alex Martelli aleax@aleax.it
Fri, 19 Jul 2002 16:39:11 +0200


On Friday 19 July 2002 04:23 pm, Aahz wrote:
> On Fri, Jul 19, 2002, Ka-Ping Yee wrote:
> > I believe this is where the biggest debate lies: whether "for" should be
> > non-destructive.  I realize we are currently on the other side of the
> > fence, but i foresee enough potential pain that i would like you to
> > consider the value of keeping "for" loops non-destructive.
>
> Consider
>
>     for line in f.readlines():
>
> in any version of Python.  Adding iterators made this more convenient
> and efficient, but I just can't see your POV in the general case.

The 'for', per se, is destroying nothing here -- the object returned by
f.readlines() is destroyed by its reference count falling to 0 after the
for, just as, say:

    for c in raw_input():

or

    x = raw_input()+raw_input()

and so forth.  I.e., any object gets destroyed if there are no more
references to it -- that's a completely different issue.  In all of these
cases, you can, if you want, just bind a name to the object as you
call the function, then use that object over and over again at will.

_Method calls_ mutating the object on which they're called is indeed
quite common, of course.  f.readlines() does mutate f's state.  But
the object it returns, as long as there are references to it, remains.


Alex