Skip to content

Problem with classmethods in generic protocols #10081

@SergeyTsaplin

Description

@SergeyTsaplin

To Reproduce

I have the following protocol:

from typing import Protocol, TypeVar, Dict, Type

ModelType = TypeVar("ModelType", bound="DictSerializable")


class DictSerializable(Protocol):
    @classmethod
    def from_dict(cls: Type[ModelType], data: Dict) -> ModelType:
        ...

    def to_dict(self: ModelType) -> Dict:

With the following usage:

from dataclasses import dataclass

@dataclass
class Item:
    value: int

    @classmethod
    def from_dict(cls: Type[Item], data: Dict) -> Item:
        return Item(value=data["value"])

    def to_dict(self) -> Dict:
        return {"value": self.value}


item: DictSerializable = Item(value=1)

Expected Behavior

I expect that there is no error

Actual Behavior

The mypy output:

main.py:29: error: Incompatible types in assignment (expression has type "Item", variable has type "DictSerializable")
main.py:29: note: Following member(s) of "Item" have conflicts:
main.py:29: note:     Expected:
main.py:29: note:         def from_dict(cls, data: Dict[Any, Any]) -> <nothing>
main.py:29: note:     Got:
main.py:29: note:         def from_dict(cls, data: Dict[Any, Any]) -> Item
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.800
  • Mypy command-line flags: -
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.9
  • Operating system and version: Any

Note

There is no chance to change the Item because it's generated by some 3rd party tool, so using the instance methods instead of classmethods are not suitable.

Mypy playground link: https://mypy-play.net/?mypy=latest&python=3.9&gist=cd5f30078d13e2cac70376a0bdc2ff06

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions