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
{{ message }}
Repository navigation
isinstance + class indirectly deriving from SupportsInt results in "TypeError: Protocols cannot be used with isinstance()" #297
% python code3.py
42
Traceback (most recent call last):
File "code3.py", line 16, in <module>
print(isinstance(c, C1))
File "/usr/local/Cellar/python3/3.5.2_2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/typing.py", line 1269, in __instancecheck__
raise TypeError("Protocols cannot be used with isinstance().")
TypeError: Protocols cannot be used with isinstance().
It seems that I'm put in a situation where I have to choose between static type safety and having the code actually work, am I missing something here? If not - what's the recommended solution to a problem like this?
I have a pretty straightforward fix, which still disallows isinstance() checks on classes that directly derive from _Protocol (such as SupportsAbs) but allows it for subclasses thereof (like your C1 and C2).
diff --git a/src/typing.py b/src/typing.py
index c4f0fdc..a87500c 100644
--- a/src/typing.py
+++ b/src/typing.py
@@ -1440,6 +1440,8 @@ class _ProtocolMeta(GenericMeta):
"""
def __instancecheck__(self, obj):
+ if _Protocol not in self.__bases__:
+ return super().__instancecheck__(obj)
raise TypeError("Protocols cannot be used with isinstance().")
def __subclasscheck__(self, cls):
@gvanrossum As a quick fix this is perfectly OK. I would say that for a permanent fix we could think about making the rules the same as for ordinary generics. But before deciding on permanent solution, I would ask @JukkaL for his opinion (the permanent fix would probably depend on resolution of #11).
Activity
gvanrossum commentedon Oct 12, 2016
This is definitely a problem. A quick workaround would be to replace the import with
but that's pretty gross.
I have a pretty straightforward fix, which still disallows isinstance() checks on classes that directly derive from _Protocol (such as SupportsAbs) but allows it for subclasses thereof (like your C1 and C2).
@ilevkivskyi What do you think of that fix?
gvanrossum commentedon Oct 12, 2016
PS. The fix only works on top of #295.
ilevkivskyi commentedon Oct 12, 2016
@gvanrossum As a quick fix this is perfectly OK. I would say that for a permanent fix we could think about making the rules the same as for ordinary generics. But before deciding on permanent solution, I would ask @JukkaL for his opinion (the permanent fix would probably depend on resolution of #11).
jstasiak commentedon Oct 13, 2016
Thanks @gvanrossum, I totally forgot about the
TYPE_CHECKINGvariable, I'll use the workaround you mentioned for the time being.Fix isinstance() for Protocols (#330)