[New-bugs-announce] [issue13667] __contains__ method behavior

João Bernardo report at bugs.python.org
Wed Dec 28 10:11:10 CET 2011

New submission from João Bernardo <jbvsmo at gmail.com>:

Hi, I'm working on a class which implements the __contains__ method but the way I would like it to work is by generating an object that will be evaluated later.

It'll return a custom object instead of True/False

class C:
    def __contains__(self, x):
        return "I will evaluate this thing later... Don't bother now"

but when I do:

>>> 1 in C()

It seems to evaluate the answer with bool!

Reading the docs (http://docs.python.org/py3k/reference/expressions.html#membership-test-details) It says:

"`x in y` is true if and only if `y.__contains__(x)` is true."

It looks like the docs doesn't match the code and the code is trying to mimic the behavior of lists/tuples where "x in y" is the same as

any(x is e or x == e for e in y)

and always yield True or False.

There is a reason why it is that way?


assignee: docs at python
components: Documentation, Interpreter Core
messages: 150283
nosy: JBernardo, docs at python
priority: normal
severity: normal
status: open
title: __contains__ method behavior
type: behavior
versions: Python 3.2, Python 3.3

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list