? 'in' operator and fallback to __getitem__

Jeff McNeil jeff at jmcneil.net
Mon May 18 13:15:19 EDT 2009


On May 18, 11:31 am, Tim Hoffman <zutes... at gmail.com> wrote:
> Hi Marco
>
> Thats definately what I think is happening.
>
> I tried the following
>
> >>> class yy(object):
>
> ...   def __getitem__(self,name):
> ...     raise KeyError(name)
> ...   def __contains__(self,name):
> ...     raise KeyError(name)
> ...>>> aa = yy()
> >>> 'll' in aa
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 5, in __contains__
> KeyError: 'll'>>> [i in aa]
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'i' is not defined>>> [i for i in aa]
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 3, in __getitem__
> KeyError: 0
>
>
>
> Which suggests to me there must be some sort of order of precedence
> between __contains__ and __getitem__
> and 'for' statement must change the order in some manner.
>
> Thanks for the reply
>
> T
>
> On May 18, 11:24 pm, Marco Mariani <ma... at sferacarta.com> wrote:
>
> > timh wrote:
> > > 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
>
> > I think it's scanning the container as a sequence and not as a mapping,
> > hence the access by index.
>
>

Whoops, I just realized I posted the wrong link...

http://docs.python.org/reference/expressions.html#in

Jeff



More information about the Python-list mailing list