[Python-Dev] Single- vs. Multi-pass iterability
Alex Martelli
aleax@aleax.it
Tue, 16 Jul 2002 15:29:17 +0200
On Tuesday 16 July 2002 02:52 pm, Guido van Rossum wrote:
...
> argue that making the file object its own iterator is only confusing;
> given that I'm also not sure what problem it solves, I'm at best +0 on
Personally, I think it solves at least a teaching problem -- it helps me
teach the difference between iterators and iterables. In the Europython
tutorial I had to gloss a bit over the fact that the difference was rather
blurried. According to the principles I mentioned, as easiest for the
audience to understand and apply, the file object SHOULD have been
an iterator, not an iterable -- i.e. it SHOULD have been the case that
f is iter(f) when f is a file object -- but it wasn't. When it IS, that's one
less micro-wart I need to mention when teaching or writing about it.
I don't see any downside to having this micro-wart removed. In
particular, I don't see what's confusing. Things that respond to
iter(x) fall in two categories:
iterators: also have x.next(), and iter(x) is x
iterables: iter(x) is not x, so you can presumably get another
iterator out of x at some later point in time if needed.
It's not QUITE as simple as this, but moving file objects from
the second category to the first seems to _simplify_ things a bit.
E.g.:
def useIterable(x):
try:
it = iter(x)
except TypeError:
raise TypeError, "Need iterable object, not %s" % type(x)
if it is x:
raise TypeError, "Need iterable object, not iterator"
# keep happily using it and/or x as needed, and in particular
# the code is able to call it1 = iter(x) if it needs to iterate again
Not perfect -- but having a file-object argument fail this simplistic
test seems better to me, less confusing, than having it pass.
So, I, personally, am +1. It might be even nicer (from the point of view
of teaching, at least) if iterating on f interoperated more smoothly with
other method calls on f, but I do see your point that the right way
to achieve THAT would be a complete rewrite of the I/O system,
and thus a vastly heavier project than the current one. Still, the current
step seems to be in the right direction.
Alex