[Python-3000] Iterators for dict keys, values, and items == annoying :)

Guido van Rossum guido at python.org
Fri Mar 24 02:06:30 CET 2006


On 3/23/06, Brett Cannon <brett at python.org> wrote:
> On 3/23/06, Ian Bicking <ianb at colorstudy.com> wrote:
> > When I was just
> > first learning Python I thought this would work:
> >
> >    for item in select_results:
> >        ...
> >    else:
> >        ... stuff when there are no items ...
> >
> > But it doesn't work like that.
>
> I have to admit that is what I initially thought as well.  I think it
> is because when I read 'else' I viewed it as an alternative if the
> clause it was attached to didn't happen (ala an 'if' statement).
> Obviously Python has broken me of that habit of thinking of it that
> way, but I bet most people are used to 'else' working like that.
>
> Would be nice to have a an easy way to specify what to do if the loop
> didn't execute.  But that would require a keyword.  Otherwise we
> should really include the idiom of having a boolean that gets set
> within the loop as part of the docs (or some Python Best Practices doc
> in terms of using loops or something).

But this is only needed if *all you have* is the iterator. Most of the
time, the code containing the for loop has access to the container,
and the iterator is only instantiated by the __iter__() call implied
by the for loop. (Off-topic: maybe we can drop the fall-back behavior
of iter() if __iter__ isn't found?)

So the common pattern is simply this:

  if not container:
    ...it's empty...
  else:
    for item in container:
      ...handle items...

The pattern with the 'empty' flag is only needed when due to API
constraints you have only got an iterator. I don't think that's very
common -- IMO SQLobject just made a poor choice there. It would have
made more sense if its query object conceptually represented the
*result set* and iterating over it was just the way of accessing the
items of the result set.

Even if you're iterating over the lines of a file, can do without the
'empty' flag pattern -- you can simply stat the file to see whether
it's empty or not.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list