? 'in' operator and fallback to __getitem__

timh zutesmog at gmail.com
Mon May 18 11:22:30 EDT 2009


Hi

I am trying to understand something about how the 'in' operator (as in
the following expression)

if 'aa' in x:
   do_something()

When trying to implement in support on a class it appears that if
__contains__ doesn't exist
in falls back to calling __getitem__

However strange things happen to the name passed to __getitem__ in the
following example (and in fact in all varients I have triend the name/
key passed to __getitem__ is always the integer 0

For instance

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class xx(object):
...    def __getitem__(self,name):
...       raise KeyError(name)
...
>>> aa = xx()
>>> aa['kk']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __getitem__
KeyError: 'kk'
>>> 'kk' in aa
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __getitem__
KeyError: 0


I am running on ubuntu, and this happens to 2.5.4 as well.  I must say
I am surprised and
am at a loss as to what is actually going on.

Can anyone enlighten me (or should I go and read some 'c' code ;-)

Rgds

Tim



More information about the Python-list mailing list