Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stronger typing for request.headers.get method #2128

Closed
pcorpet opened this issue May 16, 2021 · 1 comment · Fixed by #2129
Closed

Stronger typing for request.headers.get method #2128

pcorpet opened this issue May 16, 2021 · 1 comment · Fixed by #2129
Milestone

Comments

@pcorpet
Copy link
Contributor

pcorpet commented May 16, 2021

Since v2 and the typing stubs, the get method of the Headers data structure always returns a Optional[str]. However in some cases we can know statically that it will return a str. Indeed when a default string parameter is given, then the function always return a str.

Here's a preview of my code before v2:

auth_token = flask.request.headers.get('Authorization', '').replace('Bearer ', '')

Now that werkzeug is typed, the .replace will raise an typing error when analyzed with mypy.

error: Item "None" of "Optional[str]" has no attribute "replace"

I can fix it like this:

auth_token = typing.cast(str, flask.request.headers.get('Authorization', '')).replace('Bearer ', '')

or even like this

auth_header = flask.request.headers.get('Authorization', '')
if auth_header:
  auth_token = auth_header.replace('Bearer ', '')
else:
  auth_token = ''

But I feel like all of those patches shouldn't be required. I'll send a type fix.

@ThiefMaster
Copy link
Member

I guess we need an @overload definition for get and similar methods... like here: https://github.com/python/typeshed/blob/a7302dc6cb9527ba8cb014327e29c035d991550f/stdlib/typing.pyi#L443-L446

@davidism davidism added this to the 2.0.1 milestone May 17, 2021
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 1, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants