Compatibility of protocol class object with `type[T]` and `type[Any]`

mypy’s behaviour is probably incorrect, but I’m less sure about which direction — whether it should match pyright and permit everything, or error in all cases. Note both pyright and mypy also permit type[object], so don’t think there’s anything particularly special happening with type[Any].


(more broadly, but also more off-topic-ly)

I’m not sure how successful “only concrete class can be given” check is at all. PEP 544 says it’s meant to disallow instantiation of abstract types. I think I’d prefer if direct instantiation of a cls: type[Proto] was what was disallowed and you were forced to pass in Callable[..., Proto] if you wanted to do cls(...). This would also help with __init__ unsoundness.

This came up recently in Reason given for disallowing non-concrete subtype assignment is unsound · Issue #1647 · python/typing · GitHub. Also see Use case for typing.Type with abstract types · Issue #4717 · python/mypy · GitHub where there’s pretty strong evidence users don’t like this check as currently implemented in mypy. (Note that mypy’s behaviour is different than pyright’s, e.g. it also subjects ABCs to this constraint, again as a means of disallowing instantiation of an abstract type)

Note this check does get you some other things not mentioned in PEP 544, like avoiding isinstance on non-runtime-checkable Protocols

8 Likes