Best solution (Re: Discussion about PEP 234: iterators)

Huaiyu Zhu hzhu at users.sourceforge.net
Mon Feb 19 22:23:22 EST 2001


On Mon, 19 Feb 2001 03:32:41 GMT, Jeff Petkau <jpet at eskimo.com> wrote:

>- make 'dict.keys' return the proxy object, which is
>  callable.  Make proxy.__call__() return an actual
>  list from the proxy so dict.keys() works as before.
>  So cute I'm ashamed I even thought of it.

What a bright idea!  This is the best solution I've seen so far.  I'm
surprised no one has commented on this yet.  So let me spell it out to
generate more interest.

With this proposal, all of these work as expected

for k in dict.keys:
for k, v in dict.items:
for v in dict.values:

without creating extra list.  And all of these work as expected

if k in dict.keys:
if k, v in dict.items:
if v in dict.values:

Only the last need linear search, which is natural.

There will be no confusion over what 'in' means for dict.  There is no
clutter of code.  And "explicit is better than implicit".

Furthermore, all the old codes work as well, like

a = dict.keys()
v = dict.values()[3]
x, y = dict.items()[2]

Whatever the actual implementation would be, this seems to offer the
cleanest syntax space for iterators and has_item proxies and so on whenever
they become available.  

In the actual implementation, all iterators need to provide three magical
methods: __getitem__, __contains__ and __call__ with the usual sematic
restrictions:

__contains__ return true iff __getitem__ will get it at least once.
__call__ will return a list of objects returned by __getitem__.
__getitem__ raise IndexError at the end.


Huaiyu




More information about the Python-list mailing list