Does assert_type is supposed to work with Protocol?
#1819
Answered
by
JelleZijlstra
rayansostenes
asked this question in
Q&A
|
Does from typing import Protocol, assert_type
class MyProtocol(Protocol):
def my_method(self) -> None:
...
class Concrete:
def my_method(self) -> None:
...
x: MyProtocol = Concrete() # OK
assert_type(Concrete(), MyProtocol) # "assert_type" mismatch: expected "MyProtocol" but received "Concrete" MyPy has a similar error: error: Expression is of type "Concrete", not "MyProtocol" [assert-type]
|
Answered by
JelleZijlstra
Jul 24, 2024
Replies: 1 comment 7 replies
|
There is a specification at https://typing.readthedocs.io/en/latest/spec/directives.html#assert-type but it could be made more precise. |
7 replies
Answer selected by
rayansostenes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
assert_type()works with protocols, but it checks for an exact match, not for assignability. To check thatConcreteis assignable to MyProtocol, it is enough to do e.g.x: MyProtocol = Concrete().There is a specification at https://typing.readthedocs.io/en/latest/spec/directives.html#assert-type but it could be made more precise.