Special Method Protocols

__contains__() — containers protocol

Implement membership testing with in and not in. Python truth-tests the returned value. If absent, membership tries iteration and then sequence indexing. Mapping membership conventionally checks keys.

Formal Syntax & Structure

python syntaxpython
def __contains__(self, item):

Parameters & Attributes

NameTypeDescription
itemobjectMembership candidate.

Return Value

object

Truth-tested membership result.

Working Example

Example Snippetpython
class Allowed:    def __contains__(self,item): return item in ("read","write")print("read" in Allowed())
Python Reference