Skip to content

Class inheriting from property doesn't typecheck properly when used as a decorator #6158

Open
@matthchr

Description

@matthchr

I have a custom class inheriting from property. When I go to use this as a decorator though mypy seems to miss that it's a property at all. This is with Python 3.6.3 and mypy 0.650.

Example:

class CustomProperty(property):
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        super().__init__(fget, fset, fdel, doc)

class A:
    def __init__(self) -> None:
        self._val = 1

    @CustomProperty
    def val(self) -> int:
        return self._val

    @val.setter
    def val(self, v: int) -> None:
        self._val = v


def test_a() -> None:
    print(A.val)

Running mypy on this gives the following output:
mypy minimal2.py

minimal.py:14: error: Name 'val' already defined on line 10
minimal.py:14: error: Name 'val' is not defined
minimal.py:20: error: "Type[A]" has no attribute "val"

Contrast this with the same code with the builtin property which typechecks fine:

class B:
    def __init__(self) -> None:
        self._val = 1

    @property
    def val(self) -> int:
        return self._val

    @val.setter
    def val(self, v: int) -> None:
        self._val = v

def test_b() -> None:
    print(B.val)

It's possible that this is related to #1529 where @ilevkivskyi suggested that:

The original example now passes mypy, not sure however how useful the subclass can be (property is heavily special-cased in mypy), but at least the original bug is fixed, so closing this.

Is subclassing property frowned upon (or just not supported in mypy?).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions