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

James_Althoff at i2.com James_Althoff at i2.com
Mon Mar 18 16:02:48 EST 2002


[huaiyu]
|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.

They have to do *something*.  They have to make sure that A supports
whatever protocol is assumed in the implementation of the "items" function.
That is, A *has* to be a "sequence" or whatever is assumed by items().

|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.

But that also means that it *will* work if A.items is defined even if A
does not implement every "sequence" method.  So A.items is *more* general
than items(A) in that sense.  items(A) becomes more general only if it
first tries to call A.items (or A.__items__, or whatever) and failing that
then tries to use a sequence or other protocol as a back up.  If not, then
you are *restricting* things to "sequences" only (or whatever else happens
to be hardcoded in the items() function implementation).

|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.

Or, depending on how you think of it, it provides *generality* to the
users.

Jim





More information about the Python-list mailing list