Skip to content

Abstract settable properties are not fully supported #13649

Open
@sobolevn

Description

@sobolevn

Python docs say that properties can have individual abstract parts: https://docs.python.org/3/library/abc.html#abc.abstractproperty

So, let's see what mypy thinks about it.

abstract getter

import abc

class Base(abc.ABC):
    @property
    @abc.abstractmethod
    def x(self) -> int: ...

class Child(Base):
    ...

c = Child()  # error: Cannot instantiate abstract class "Child" with abstract attribute "x"

It is supported ✅

abstract setter

import abc

class Base(abc.ABC):
    @property
    def x(self) -> int: ...

    @x.setter
    @abc.abstractmethod
    def x(self, arg: int) -> None: ...

class Child(Base):
    ...

c = Child()
c.x = 2
reveal_type(c)  # Revealed type is "ex.Child"
# Runtime:
# TypeError: Can't instantiate abstract class Child with abstract method x

Not supported 🚫

Should instead say: # error: Cannot instantiate abstract class "Child" with abstract attribute "x"
Or even better with abstract property setter "x"

abstract getter and setter

import abc

class Base(abc.ABC):
    @property
    @abc.abstractmethod
    def x(self) -> int: ...

    @x.setter
    @abc.abstractmethod
    def x(self, arg: int) -> None: ...

class Child(Base):
    ...

c = Child()  # E: Cannot instantiate abstract class "Child" with abstract attribute "x"

However, this does not fully cover this case:

import abc

class Base(abc.ABC):
    @property
    @abc.abstractmethod
    def x(self) -> int: ...

    @x.setter
    @abc.abstractmethod
    def x(self, arg: int) -> None: ...

class Child(Base):
    @property  # E: Read-only property cannot override read-write property
    def x(self) -> int: ...

Child()  # ok

We can add additional note about x.setter being abstract. Or we can keep this as is.

Related:

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