Repository navigation
del state.missing raises KeyError instead of AttributeError
#3644
Unanswered
sungbin1015
asked this question in
Potential Issue
Replies: 1 comment
|
Reproduced on current main (0a15da3). starlette/starlette/datastructures.py Lines 689 to 697 in 0a15da3 Until it's changed, either of these works on current releases:
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
State.__getattr__converts theKeyErrorfrom the underlying dict into anAttributeError, butState.__delattr__does not, so deleting an attribute that is not set leaks a bareKeyError:Output on
main(ff5b4df and later, Python 3.11):Expected:
del state.missing/delattr(state, "missing")raiseAttributeError, likegetattrdoes and like any regular object. Code that guards an optional cleanup withexcept AttributeErrororcontextlib.suppress(AttributeError)arounddel request.state.xdoes not catch the current exception.The cause is in
starlette/datastructures.py:__delitem__raisingKeyErroris correct for the mapping-style access; only the attribute-style__delattr__looks inconsistent. A fix would be the sametry/except KeyErroras in__getattr__. I'm not opening a PR for it; if you agree it is a bug it is a two-line change either way.Related work. I searched discussions, issues and PRs (open and closed) for
State __delattr__,delattr KeyError stateandrequest.state del attribute KeyError. The closest are #2995 (asks whether an attribute can be removed fromapp.state; the answer showsdel app.state.stufffor an existing attribute) and #2389 (asks for astate.get). Neither mentions the exception type for a missing attribute, and none of the open PRs that touchstarlette/datastructures.pychangesState.Found with AI assistance (Claude Code) and reproduced locally with the snippet above.
All reactions