set session.headers to MutableMapping#9395
Conversation
This comment has been minimized.
This comment has been minimized.
2c74b5a to
5528de7
Compare
This comment has been minimized.
This comment has been minimized.
| headers: CaseInsensitiveDict[str | bytes] | ||
| # See https://github.com/psf/requests/issues/5020#issuecomment-989082461: | ||
| # requests sets this as a CaseInsensitiveDict, but users may set it to any MutableMapping | ||
| headers: MutableMapping[str, str | bytes | None] |
There was a problem hiding this comment.
Are you sure this should be MutableMapping[str, str | bytes | None] rather than MutableMapping[str, str | bytes]? This annotation was debated somewhat extensively in #7773 (comment). @janrito said at the time:
We want to allow str or bytes on actual headers, but None only on updates
There was a problem hiding this comment.
No, I am not sure. But given that this code does not produce any runtime error:
session = requests.Session()
session.headers = None
resp = session.get('http://example.com')
assert resp.status_code == 200It appears headers get merged-or-set-to-defaults with None? https://github.com/psf/requests/blob/main/requests/sessions.py#L61-L71
Edit for clarity: I'm open to any guidance on whether type checking should reflect runtime behavior or do "something else."
There was a problem hiding this comment.
If it's okay to set session.headers to None, then the annotation should be headers: MutableMapping[str, str | bytes] | None rather than MutableMapping[str, str | bytes | None]
There was a problem hiding this comment.
From the mypy_primer output, looks like changing it to MutableMapping[str, str | bytes] | None would be quite disruptive -- so I vote for keeping this as MutableMapping[str, str | bytes] for now, unless keeping it that way is causing a concrete problem for you.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Thanks @evilensky! Will merge once the CI has finished.
requests is tricky to write stubs for, there's loads of unexpected things that crop up...
|
According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉 |
Resolves #9390.
The session.headers may be set to any mapping according to the project, and mutable mapping appears to be the most correct annotation.