Skip to content

Inconsistent Treatment of Class Constructor by Protocol #10482

Closed
@rmorshea

Description

@rmorshea

In the code below we define one protocol which, when called, returns another. In effect we're describing a "factory". However, while MyPy is able to recognize incorrect protocol implementations when given a function, it fails to do the same for class constructors.

Playground link: https://mypy-play.net/?mypy=latest&python=3.9&gist=3b9250b17032b659fc36746e659bcdb5

from typing import Protocol

class Factory(Protocol):
    def __call__(self) -> Result:
        ...

class Result(Protocol):
    a: int
    
class BadImplementation:
    ...

def bad_implementation() -> BadImplementation:
    ...

something: Factory = BadImplementation  # no error
something_else: Factory = bad_implementation  # yes error

We would expect MyPy to give an error in both cases given they result in the same type, but it only complains when given a standard function.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions