"in" for dicts (was: Python 2.1 function attributes)

Thomas Wouters thomas at xs4all.net
Mon Jan 29 05:53:31 EST 2001


On Mon, Jan 29, 2001 at 04:24:22AM -0500, Tim Peters wrote:
> [Nathaniel Gray]
> > ...
> > Nevertheless, there are still three big problems with "in" for
> > dictionaries:
> >
> > Number 1:  There is no reason, a priori, to think that "in dict" should
> > mean "in dict.keys()" rather than "in dict.values()" or even "in
> > dict.items()".  Explicit is better than implicit, right?
> 
> This is the reason Guido gave most often in previous years.  It appears
> that only professional debaters *believe* it, though <wink>.  That is, to
> the best of my knowledge, nobody ever claimed that they personally would
> mistake what
> 
>     if x in dict:
> 
> or
> 
>     for x in dict:
> 
> meant.  They're always worred that "somebody else" might not get it. 
> After a decade, it's increasingly hard to believe that set of
> supernaturally feeble users isn't empty.

Two of my colleagues (out of two interrogated) didn't quite get it. It's not
that they didn't understand the idea, but it wasn't quite what they
expected. They aren't quite feeble :) But it's also true that their
expectations were different in the 'for' case. 

My main beef with the 'x in dict' idea is something Nathaniel didn't raise,
though: we all seem to think 'x in dict' is naturally 'key in dict' -- but
why ? Is it because we all know you can't *get* a value from a dict without
extracting them all, and all values could be the same ? How obvious is that
to people without a technical idea of dictionaries ? What, exactly, is the
target group for Python ? :)

> > Number 5:  (three, sir)  Oh yes, number 3:  We've already got "for a_key
> > in dict.keys()"!
> 
> We still don't have anything else for 2.1; only "a_key in dict" in a
> *boolean* context has been implemented.  And, yes, we've already got
> dict.has_key(a_key) for that.  And, yes, Guido just *approved* of adding
> "for a_key in dict" too, although implementing that is a puzzle given the
> current iteration protocol's use of __getitem__ (it doesn't jibe with what
> dict.__getitem__ does), and "what to do" about programs that go mutating
> the dict during iteration.

I haven't seen Guido approve of 'for x in dict' yet, though. Was this in
private mail/conversations, or did the PSU try to prevent me from getting
*another* free alpha release plus sexy one-use license ? ;-) If Guido
did/does approve of 'for x in dict', it might be a good excuse to invent an
iteration protocol. Hacking the FOR_LOOP opcode to special case mapping
types isn't that hard, though it wouldn't be usable by class instances.

Further fleshing out of the iteration protocol would probably have to wait
until Python 2.2, if only for the fact it really needs a real PEP :)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list