Monday, 15 October 2018

Type incompatibility for subclass' decorated method - python

I'm getting an error

$ mypy python.py
python.py:34: error: Signature of "fn" incompatible with supertype "B"

where python.py is

from typing import Callable, TypeVar, cast

T = TypeVar('T')


def dec(f: Callable[..., T]) -> T:
    def p(self):
        return getattr(self, '_' + f.__name__)

    return cast(T, property(p))


class X:
    pass


class Y(X):
    pass


class A:
    def _fn(self) -> X:
        return X()


class B(A):
    @dec
    def fn(self) -> X:
        return X()


class C(B):
    @dec
    def fn(self) -> Y:
        return Y()

Here, the decorator dec is meant to do two things

  • promote the corresponding method to a property
  • redirect the call to a method whose name has an additional underscore

I don't understand why mypy can't work out that Y inherits from X. There's no error if I replace -> Y with -> X.

I've tried this with mypy 0.630 and Python 3.5.2, 3.6.6 and 3.7.0



from Type incompatibility for subclass' decorated method - python

No comments:

Post a Comment