Add __contains__, __eq__, and __repr__ to State#3155
Closed
bysiber wants to merge 1 commit intoKludex:mainfrom
Closed
Add __contains__, __eq__, and __repr__ to State#3155bysiber wants to merge 1 commit intoKludex:mainfrom
bysiber wants to merge 1 commit intoKludex:mainfrom
Conversation
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...>'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The
Stateclass (used forrequest.stateandapp.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 statefalls 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).__eq__Allows direct comparison of
Stateobjects, which is particularly useful in tests. ReturnsNotImplementedfor non-State comparisons so Python can try the other operand's__eq__.__repr__Provides a readable representation instead of the default
<State object at 0x...>, making debugging significantly easier.