Created
October 31, 2020 11:52
-
-
Save nobbynobbs/4a18b4f4466a7eee58d44b5bfcf10532 to your computer and use it in GitHub Desktop.
generic descriptor and inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: | |
@classmethod | |
def construct(cls: Type[T]) -> T: | |
return cls() | |
def me(self: T) -> T: | |
return self | |
attr: int = 123 | |
descr = Descr[T]() # doesn't work | |
class B(A): | |
new_attr: int = 123 | |
qwerty: str = "qwe" | |
if __name__ == "__main__": | |
a = A().construct() | |
if TYPE_CHECKING: | |
reveal_type(a) # A*, ok | |
reveal_type(a.me()) # A*, ok | |
reveal_type(a.descr) # T? | |
print("a.attr =", a.descr.attr) # T? has no attribute "attr" | |
# no runtime error | |
b = B().construct() | |
if TYPE_CHECKING: | |
reveal_type(b) # B*, ok | |
reveal_type(b.me()) # B*, ok | |
reveal_type(b.descr) #T? | |
print("b.new_attr =", b.descr.new_attr) # T? has no attribute "new_attr" | |
# no runtime error | |
print("b.qwerty =", b.descr.qwerty) # T? has no attribute "qwerty" | |
# no runtime error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment