? 'in' operator and fallback to __getitem__

Tim Hoffman zutesmog at gmail.com
Mon May 18 11:31:53 EDT 2009


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.




More information about the Python-list mailing list