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

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

Stronger typing for request.headers.get method #2128

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


Copy link

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 ', '')
  auth_token = ''

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

Copy link

I guess we need an @overload definition for get and similar methods... like here:

@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.
None yet
None yet

Successfully merging a pull request may close this issue.

3 participants