[Python-Dev] Why is the return value of __contains__ coerced to boolean, but that of __lt__ and the like is not?

Steven D'Aprano steve at pearwood.info
Mon Jul 15 05:47:56 CEST 2013


On Mon, Jul 15, 2013 at 03:34:08PM +1200, Ben Hoyt wrote:
> Thanks, Nick -- that's helpful info. Writing such a PEP is a nice idea, but
> I think it'd be beyond me (I'm not familiar enough with CPython internals,
> protocols, etc).
> 
> Can you explain what you mean by "symmetric protocol rather than the
> current only-controlled-by-the-container behaviour"?

Most operators can be controlled by either the left-hand or right-hand 
operand. For example, x + y can end up calling either x.__add__(y) or 
y.__radd_(x). The `in` operator is an exception, it only ever calls the 
container:

x in y => y.__contains__(x)

but never x.__contained_by__(y)



-- 
Steven


More information about the Python-Dev mailing list