-
Notifications
You must be signed in to change notification settings - Fork 287
-
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?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
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 (useAnyinstead, 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
Protocolreturnsstr, but the implementation returnsstr | 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 apropertyinstead.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 2