bhylu.com

Advertisements

__contains__

__contains__ defines membership for a custom object. It should match the question a caller expects the in operator to ask.

Understand the idea

A roster's membership asks whether a name is registered. A dictionary-like type might instead define membership over keys. Python can fall back to iteration when __contains__ is absent, but a direct implementation can make the meaning and performance clearer. Keep case normalization policy explicit rather than quietly changing names during lookup.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Roster:
    def __init__(self, names):
        self.names = set(names)
    def __contains__(self, name):
        return name in self.names

print("Mira" in Roster(["Mira", "Dev"]))

Read the result

The output is True.

Try one change

Test a differently cased name and decide whether membership should be case-sensitive for your data.