You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Both class types and protocols support isinstance for type narrowing, but TypeIs seems to be not supported for protocols because of mypy error: Narrowed type "Proto" is not a subtype of input type "X".
Adding protocols support in TypeIs would:
Enable writing general type guard functions without subclassing,
Provide feature parity between classes (isinstance + TypeIs) and protocols (isinstance only).
Using only isinstance (with @runtime_checkable protocols) is not sufficient, because type guard functions can do more strict runtime checks, and provide TypeIs for static type checkers.
Consider the example below, where hinting X.y as mandatory requires subclassing X instead of declaring independent protocol:
That error is correct and in line with how TypeIs is specified: the narrowed type must be a subtype of the non-narrowed type. You can likely get your desired behavior by annotating the parameter to has_y as object.
That error is correct and in line with how TypeIs is specified: the narrowed type must be a subtype of the non-narrowed type. You can likely get your desired behavior by annotating the parameter to has_y as object.
@JelleZijlstra thank you so much for the clarification! Using object is more than enough.
Feature
Add support for
Protocol
asTypeIs
parameter.Pitch
Both class types and protocols support
isinstance
for type narrowing, butTypeIs
seems to be not supported for protocols because of mypy error: Narrowed type "Proto" is not a subtype of input type "X".Adding protocols support in
TypeIs
would:isinstance
+TypeIs
) and protocols (isinstance
only).Using only
isinstance
(with@runtime_checkable
protocols) is not sufficient, because type guard functions can do more strict runtime checks, and provideTypeIs
for static type checkers.Consider the example below, where hinting
X.y
as mandatory requires subclassingX
instead of declaring independent protocol:The desired behavior produces mypy error
If mypy error can be easily fixed, this feature could be useful addition to Python type narrowing.
The text was updated successfully, but these errors were encountered: