Skip to content

mypy deduced type on Request.user_agent_class is Type[_UserAgent] #2273

@sirosen

Description

@sirosen

I ran into this after updating to v2.0.2 of flask and werkzeug.

Since UserAgent is going away, I replaced it with ua_parser (example will follow).
However, setting user_agent_class = MyUserAgent triggers a typing error as the type of Request.user_agent_class refers to the internal (deprecated) _UserAgent.

Absolutely minimal reproduction:

# minimal.py
from flask import Request
from werkzeug.user_agent import UserAgent

class MyUserAgent(UserAgent): pass

class MyRequest(Request):
    user_agent_class = MyUserAgent

produces

$ mypy minimal.py
minimal.py:7: error: Incompatible types in assignment (expression has type "Type[MyUserAgent]", base class "Request" defined the type as "Type[_UserAgent]")
Found 1 error in 1 file (checked 1 source file)

I've also created a simple reproduction of the failing mypy run in a repo, which includes both the above minimal example, and my usage with ua_parser.

I know that _UserAgent is going away, so maybe this doesn't matter. But I could submit a patch to change this line to read

    user_agent_class: t.Type[UserAgent] = t.cast(t.Type[UserAgent], _DeprecatedUserAgent)

I think that would solve this, since the type would be known to mypy (and other type checkers) as Type[UserAgent], and inheriting subclasses would be accepted.

Would that fix be welcome?

Also, I haven't seen any python projects establish a testing process for type annotations. Do the pallets projects have an approach if I wanted to add a test case for this?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions