Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Mypy says "Cannot instantiate protocol class", but I can. #16390

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
chrisimcevoy opened this issue Nov 2, 2023 · 2 comments
Closed

Mypy says "Cannot instantiate protocol class", but I can. #16390

chrisimcevoy opened this issue Nov 2, 2023 · 2 comments
Labels
bug mypy got something wrong

Comments

@chrisimcevoy
Copy link

chrisimcevoy commented Nov 2, 2023

Bug Report

In CPython >= 3.11, creating an instance of a Protocol class is seemingly permitted at runtime if an initialiser is declared.

However, mypy still reports that the protocol class cannot be instantiated.

I am not sure if the bug lies with mypy or CPython, but, in this edge case, Protocol behaviour at runtime seems to have diverged from mypy's understanding somewhere between Python 3.10 and 3.11.

To Reproduce

from typing import Protocol


class Spam(Protocol):

    def __init__(self):
        print("No TypeError here!")


s = Spam()

Actual Behavior

$ python spam.py 
No TypeError here!
$ mypy spam.py 
spam.py:10: error: Cannot instantiate protocol class "Spam"  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.6.1 (compiled: yes)
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.11.5
@chrisimcevoy chrisimcevoy added the bug mypy got something wrong label Nov 2, 2023
@erictraut
Copy link

PEP 544 (which introduced Protocols to the type system) is clear on this point:

Protocols cannot be instantiated, so there are no values whose runtime type is a protocol.

So I think mypy is correct in reporting this error, at least according to the typing spec. Other type checkers like pyright report the same error here.

@hauntsaninja
Copy link
Collaborator

Yes, mypy is correct. For runtime behaviour, see (the last few comments of) python/cpython#88970

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants