I want to create a decorator that adds a member to the decorated class
that is instance of outer class.
In this case, decorator memberclass adds attribute self to the instance of class y that is of type X
class memberclass[Y]:
def __init__(self, cls: type[Y]):
self.cls = cls
def __get__(self, x, cls) -> Y | type[Y]:
if x is None: return self.cls
# I deleted some lines related to memorizing y per instance of X
y = self.cls()
y.self = x
return y
class X:
z: int
@memberclass
class y:
def f(self):
# self.self is instace of X
# type checker should be aware of self.self.z
# X.y is class y
# X().y is instance of that class
# X().y.self is X()
My best guess would be that there might be some way
to annotate __get__ method to say "Y is getting a new member self with type typeof x".
I checked whole documentation https://docs.python.org/3/library/typing.html and didn't find solution.
This also didn't help How to type hint python magic __get__ method since it doesn't show how to modify type
This also didn't help Is it possible to change method type annotations for a class instance? since it modifies function signature, but not the class members
Xclass doesn't exist when@memberclassis called. The class isn't defined until after the end of theclass X:block.self: Xtoclass ywould work, but is redundant