? 'in' operator and fallback to __getitem__

Jeff McNeil jeff at jmcneil.net
Mon May 18 11:31:44 EDT 2009


On May 18, 11:22 am, timh <zutes... at gmail.com> wrote:
> 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

See http://docs.python.org/library/functions.html#iter, that ought to
clear it up.

Thanks,

Jeff
mcjeff.blogspot.com



More information about the Python-list mailing list