[New-bugs-announce] [issue16011] "in" should be consistent with return value of __contains__

Neal Parikh report at bugs.python.org
Mon Sep 24 02:13:51 CEST 2012

New submission from Neal Parikh:

The Python 2.7.3 documentation says the following about defining __contains__:

"Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs."

This suggests that while you should return True/False, you don't need to. Also, the documentation doesn't say that if you return a value other than True or False, it will silently coerce other values to be True or False when you use "in". For example:

>>> class Foo(object):
...     def __contains__(self, item): return 42
>>> foo = Foo()
>>> 3 in foo
>>> foo.__contains__(3)

When __contains__ is defined, "in" should return whatever __contains__ returns, even if this value is neither True nor False. That would be consistent with, for example, the comparison operators: You can return anything from __lt__ and "x < 4" will correctly pass along that value regardless of what it is.

assignee: docs at python
components: Documentation, Interpreter Core
messages: 171085
nosy: docs at python, nparikh
priority: normal
severity: normal
status: open
title: "in" should be consistent with return value of __contains__
type: behavior
versions: Python 2.7

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list