Skip to content

isinstance + class indirectly deriving from SupportsInt results in "TypeError: Protocols cannot be used with isinstance()" #297

Closed
@jstasiak

Description

@jstasiak

The following assumes mypy 0.4.5 and CPython 3.5.2.

Let's have the code:

# code3.py
class C1:

    def __int__(self) -> int:
        return 42


class C2(C1):
    pass


c = C2()
print(int(c))
print(isinstance(c, C1))

The code works:

% python code3.py 
42
True

mypy, however, will complain (as expected):

% mypy code3.py  
code3.py:12: error: Argument 1 to "int" has incompatible type "C2"; expected "Union[SupportsInt, str, bytes]"

Let's try to make mypy happy:

# code3.py
from typing import SupportsInt


class C1(SupportsInt):

    def __int__(self) -> int:
        return 42


class C2(C1):
    pass


c = C2()
print(int(c))
print(isinstance(c, C1))

Now mypy is happy but the code fails at runtime:

% 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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions