Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Why does mypy report incompatible assignment types when using Protocol? #1851

Unanswered
aj-cruz asked this question in Q&A
Discussion options

I have a class named Filter that adheres to a Protocol class named ExtractorProtocol
I confirmed an instance of the Filter class adheres to the Protocol by doing this:

self.filters: ExtractorProtocol = Filters(workbook)
print(isinstance(self.filters, ExtractorProtocol))

Which returns True

However, mypy throws the following error:
error: Incompatible types in assignment (expression has type "Filters", variable has type "ExtractorProtocol") [assignment]

Why can't I use the Protocol class in the typing?

You must be logged in to vote

Replies: 1 comment

Comment options

Without the actual Protocol and Filter definition that will be impossible to answer. It's also worth noting that runtime checkable protocols only implement a very simple check that verifies if all the required attributes exist. But it will not verify if method signatures are compatible, since that would be too expensive to check at runtime. So just because the runtime isinstance check succeeds, does not mean that the object represents a correct implementation of the Protocol and that type checker should accept the assignment.

But just to give you a few hints. Common mistakes in overly specific Protocols include:

  • Not marking parameters as positional only when the parameter name doesn't matter
  • Using parameter types that are too broad (like object), but the implementations can have more narrow parameter types (use Any instead, so you can violate the contravariance restriction)
  • Using return types that are too specific, but implementations may actually return a broader type (e.g. your Protocol returns str, but the implementation returns str | None)
  • Using a regular attribute instead of a property. Using a regular attribute means it needs to be writable, so it will not allow implementations that use a property instead.
You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /