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

Brett Cannon brett at python.org
Fri Mar 24 02:24:06 CET 2006


On 3/23/06, Guido van Rossum <guido at python.org> wrote:
> 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.

Right.  That is what I do; pass around an iterator if I know all I
need is an iterator, otherwise I have API  require the actual object
so I can get the iterator directly and perform any possible queries I
need.  I just don't know how often people think about doing that.

> (Off-topic: maybe we can drop the fall-back behavior
> of iter() if __iter__ isn't found?)
>

I say yes.  Iterators will be common enough that objects that want the
support should just directly support it.

> So the common pattern is simply this:
>
>   if not container:
>     ...it's empty...
>   else:
>     for item in container:
>       ...handle items...
>

Right.  I am really starting to think that having a group of Best
Practices essays that discuss common Python idioms might be handy. 
Part tutorial, part advanced usage, they would provide a way for
people to have a place to go to find out expected usage of things such
as iterators without having to discover this kind of thing the hard
way.  Could also help us see where possible improvements could come in
for Py3K if we write them from the perspective of 2.x, or even how
things improve if we write them for Py3K.

Basically like the HOWTOs, but for the language instead of a module
and with a better name.  =)

-Brett


More information about the Python-3000 mailing list