Search code examples
pythonpycharmpython-typing

PyCharm warning: Type of 'field' is incompatible with 'A' when implementing property from protocol


I want to define an interface for a data class, but leave open the way the data is stored. To this end, I define a protocol A for the interface and an implementation B:

class A(Protocol):
    @property
    def field(self):
        ...

    @field.setter
    def field(self, value):
        ...


class B(A):
    @property
    def field(self):
        return ""

    @field.setter
    def field(self, value):
        pass

mypy has no issues with this implementation, but PyCharm warns me that

Type of 'field' is incompatible with 'A' 

Above approach was already proposed in this answer, but PyCharm doesn't really like it.

How would I better write this?


Solution

  • This is a known bug. PyCharm's type checker just have many problems in general. Put a # noqa or # noinspection comment there and move on.


    On another note, however, the protocol could and should be made generic, so that the field's type is retained:

    from typing import Protocol, override
    
    class A[T](Protocol):
        @property
        def field(self) -> T: ...
    
        @field.setter
        def field(self, value: T) -> None: ...
    
    class B(A[str]):
        @override
        def field(self) -> str:
            return ''
    
        @override
        @field.setter
        def field(self, value: str) -> None:
            pass