Common Python Idioms
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Fri Dec 8 10:54:50 EST 2006
In <elbkp8$ket$1 at news.sap-ag.de>, Daniel Dittmar wrote:
> John Machin wrote:
>> No it doesn't look wrong to anyone who has read the docs on
>> sys.modules.
>
> My point was really that there is no obvious implementation for 'in' on
> dictionaries, so it should have been left out. And that GvR thought so
> for quite some time as well (until he got mixed up with a crowd of ex
> C++ programmers).
Maybe there's no obvious implementation for ``in`` and dictionaries but
there is the semantics of ``in`` and iterables. Dictionaries are iterable
so it's clearly defined what ``'answer' in {'answer': 42}`` should return.
In [84]: class A:
....: def __iter__(self):
....: return iter((1,2,3))
....:
In [85]: a = A()
In [86]: 2 in a
Out[86]: True
In [87]: 5 in a
Out[87]: False
If ``in`` shouldn't work with dictionaries, either `__contains__()` must
be implemented to throw an exception or dictionaries shouldn't be iterable.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list