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

Moore, Paul Paul.Moore@atosorigin.com
Fri, 19 Jul 2002 16:28:11 +0100


Ka-Ping Yee <ping@zesty.ca> writes:

> It's just not the way i expect for-loops to work.  Perhaps we
> would need to survey people for objective data, but i feel
> that most people would be surprised if
>
>     for x in y: print x
>     for x in y: print x
>
> did not print the same thing twice, or if

Overall, I think I would say "it depends". Barry pointed out that it depends
on the type of y. That's what I mean, although my intuition isn't quite that
specific by itself.

By the way, not all languages that I am aware of even have "for ... in"
constructs. Perl does, and Visual Basic does. C and C++ don't. In Perl, "for
$x (<>)" or whatever magic line noise Perl uses, does the same as Python's
"for line in f", so the same non-repeatable for issue exists there (at least
for files, and I *bet* you can do nasty things with tied variables to have
it happen elsewhere, too). Even in Visual Basic, "for each x in obj" can in
theory do anything (depending on the type of obj), much like Python.

So I think that existing practice goes against your expectation.

There *is* an issue of some sort with being able to find out whether a given
object offers reproducible for behaviour in the way you describe above. The
problem is determining real-world cases where knowing is useful. There are a
lot of theoretical issues here, but few simple, comprehensible, practical
use cases.

FWIW,

- I'm +1 for renaming next() to __next__().
- I'm +0 on dropping the requirements that iterators *must*
  implement __iter__() (as per your description of the 2
  orthogonal proposals). I'd like to see iterators strongly
  advised to implement __iter__() as returning self (and
  all built in ones doing so), but not have it mandated.
- I'm -1 on your for...from syntax.

Hope this helps,
Paul.