[Python-Dev] Re: Sets: elt in dict, lst.include - really begs for a PEP

Ka-Ping Yee ping@lfw.org
Thu, 1 Feb 2001 03:31:33 -0800 (PST)


Moshe Zadka wrote:
> Basic response: I *love* the iter(), sq_iter and __iter__
> parts.  I tremble at seeing the rest.  Why not add a method to
> dictionaries .iteritems() and do
> 
>     for (k, v) in dict.iteritems():
>         pass
> 
> (dict.iteritems() would return an an iterator to the items)

Barry Warsaw wrote:
> Moshe, I had exactly the same reaction and exactly the same idea.  I'm
> a strong -1 on introducing new syntax for this when new methods can
> handle it in a much more readable way (IMO).

I remember considering this solution when i was writing the PEP.
The problem with it is that it isn't backward-compatible.  It won't
work on existing dictionary-like objects -- it just introduces
another method that we then have to go back and implement on everything,
which kind of defeats the point of the whole proposal.  (One of the Big
Ideas is to let the 'for' syntax mean "just do whatever you have to do
to iterate" and we let it worry about the details.)

The other problem with this is that it isn't feasible in practice
unless 'for' can magically detect when the thing is a sequence and
when it's an iterator.  I don't see any obvious solution to this
(aside from "instead of an iterator, implement a whole sequence-like
object using the __getitem__ protocol" -- and then we'd be back to
square one).

I personally find this:

    for key:value in dict:

much clearer than either of these:

    for (k, v) in dict.iteritems():
    for key, value in dict.iterator(ITEMS):

There's less to read and less punctuation in the first, and there's
a natural parallel:

    seq = [1, 4, 7]
    for item in seq:
        ...

    dict = {2:3, 4:5}
    for key:value in dict:
        ...


-- ?!ng

Two links diverged in a Web, and i -- i took the one less travelled by.
    -- with apologies to Robert Frost