Skip to content

Comments

Add __contains__, __eq__, and __repr__ to State#3155

Closed
bysiber wants to merge 1 commit intoKludex:mainfrom
bysiber:add-state-dunder-methods
Closed

Add __contains__, __eq__, and __repr__ to State#3155
bysiber wants to merge 1 commit intoKludex:mainfrom
bysiber:add-state-dunder-methods

Conversation

@bysiber
Copy link

@bysiber bysiber commented Feb 20, 2026

Summary

The State class (used for request.state and app.state) was missing a few commonly expected dunder methods, making it harder to work with in tests and during debugging.

Changes

Added three methods to State:

__contains__

Without this, "key" in state falls back to __iter__, which iterates over all keys in O(n) time. With an explicit __contains__, the lookup delegates to the underlying dict in O(1).

state = State()
state.counter = 0
"counter" in state  # True, O(1or)

__eq__

Allows direct comparison of State objects, which is particularly useful in tests. Returns NotImplemented for non-State comparisons so Python can try the other operand's __eq__.

state1 = State({"a": 1})
state2 = State({"a": 1})
assert state1 == state2

__repr__

Provides a readable representation instead of the default <State object at 0x...>, making debugging significantly easier.

state = State()
state.debug = True
state.counter = 42
repr(state)  # "State(debug=True, counter=42)"

The State class is used for request.state and app.state but was
missing a few commonly expected dunder methods:

- __contains__: allows 'key in state' checks in O(1) instead of
  falling back to __iter__ which is O(n)
- __eq__: allows comparing State objects directly, useful in tests
- __repr__: provides a readable representation for debugging instead
  of the default '<State object at 0x...>'
@Kludex Kludex closed this Feb 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants