? 'in' operator and fallback to __getitem__

Dave Angel davea at ieee.org
Mon May 18 17:24:12 EDT 2009


Tim Hoffman wrote:
>
> 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
>   
>
(Please don't top-post.  It makes reading the quoted portions hard, 
since they're then out of order.   To solve the problem here, I had to 
delete the other parts)

"in" is both a keyword and an operator, with entirely different semantics.

As a keyword, it's used inside a   for statement, the expression (after 
the in) must return an iterable object.

As an operator, it's used inside an arbitrary expression.  It is this 
case which is described in the docs:

 >>>For user-defined classes which define the __contains__() 
<datamodel.html#object.__contains__> method, x in y is true if and only 
if y.__contains__(x) is true.

 >>>For user-defined classes which do not define __contains__() 
<datamodel.html#object.__contains__> and do define __getitem__(), 
<datamodel.html#object.__getitem__>
 >>> x in y is true if and only if there is a non-negative integer index 
/i/ such that x == y[i],
 >>> and all lower integer indices do not raise IndexError 
<../library/exceptions.html#exceptions.IndexError> exception. (If any 
other exception is
 >>>raised, it is as if in <#in> raised that exception).



 



More information about the Python-list mailing list