Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typing: How to bind owner class to generic descriptor?

Can I implement a generic descriptor in Python in a way it will support/respect/understand inheritance hierarchy of his owners?

It should be more clear in the code:

from typing import (
    Generic, Optional, TYPE_CHECKING,
    Type, TypeVar, Union, overload,
)

T = TypeVar("T", bound="A")  # noqa

class Descr(Generic[T]):

    @overload
    def __get__(self: "Descr[T]", instance: None, owner: Type[T]) -> "Descr[T]": ...

    @overload
    def __get__(self: "Descr[T]", instance: T, owner: Type[T]) -> T: ...

    def __get__(self: "Descr[T]", instance: Optional[T], owner: Type[T]) -> Union["Descr[T]", T]:
        if instance is None:
            return self
        return instance


class A:
    attr: int = 123
    descr = Descr[T]()  # I want to bind T here, but don't know how


class B(A):
    new_attr: int = 123
    qwerty: str = "qwe"


if __name__ == "__main__":
    a = A()
    if TYPE_CHECKING:
        reveal_type(a.descr)  # mypy guess it is T? but I want A*
    print("a.attr =", a.descr.attr)  # mypy error: T? has no attribute "attr"
                                     # no runtime error
    b = B()
    if TYPE_CHECKING:
        reveal_type(b.descr)  # mypy said it's T? but I want B*

    print("b.new_attr =", b.descr.new_attr)  # mypy error: T? has no attribute "new_attr"
                                             # no runtime error
    print("b.qwerty =", b.descr.qwerty)  # mypy error: T? has no attribute "qwerty"
                                         # (no runtime error)

gist - almost the same code snippet on gist

like image 212
NobbyNobbs Avatar asked Oct 31 '20 14:10

NobbyNobbs


Video Answer


1 Answers

I am not sure if you need to have the descriptor class as generic; it will probably just suffice to have __get__ on an instance of Type[T] to return T:

T = TypeVar("T")  # noqa

class Descr:
    @overload
    def __get__(self, instance: None, owner: Type[T]) -> "Descr": ...

    @overload
    def __get__(self, instance: T, owner: Type[T]) -> T: ...

    def __get__(self, instance: Optional[T], owner: Type[T]) -> Union["Descr", T]:
        if instance is None:
            return self
        return instance


class A:
    attr: int = 123
    descr = Descr()


class B(A):
    new_attr: int = 123
    qwerty: str = "qwe"

And every example of yours works as you wanted, and you will get an error for

print("b.spam =", b.descr.spam)

which produces

error: "B" has no attribute "spam"
like image 175