[].keys() and [].items() (Was: Why I think range is a wart)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Mon Mar 18 14:52:35 EST 2002


On Fri, 15 Mar 2002 23:58:28 -0500, Clark C . Evans <cce at clarkevans.com> wrote:
>| I think items(x) can just piggy-back on the current iterator protocol, and
>| can be made to work on any iteratable objects.
>
>Would "keys()/items()" be compatible with the iterator proposal? 
>It would be extending the iterator to return pairs... this might
>be a bit divergent...

I was not clear on this point, so let me try again.

What I meant was that if you define items(A) to return an iterator, and
write a program using 'for i,x in items(A)', it will work for any sequence
A.  Users who supply A do not need to do anything.  The implementation of
items(A) might reuse some of code implementing the implicit iterators.  But
it could be as simple as wrapping around iter(A).

On the other hand, if you define A.items(), and write a program using 'for
i,x in A.items()', it only works if A.items is defined.  If later on you
want to use it for a different kind of A, you have to make sure it has the
right .items() method.  This pushes the burden to the users of the program.

Of course we can always have both, but each program using 'for i,x in
something' has to decide what that something is.  If it is A.items(), it
puts one more constraint on A.  If we do not check the growth of such
constraints, eventually those collection classes would become like Java
collection classes with many methods that are rarely used but has to be
there just in case they might be needed in some situations.


Huaiyu



More information about the Python-list mailing list