Consider the following code:
class MyCustomDescriptor:
def __init__(self,foo):
self._foo = foo
def __call__(self,decorated_method):
# Here's my question... Is there any way to get a reference to the
# type (ClassA or ClassB) here?
return self
def __get__(self,instance,type):
# Clearly at this point I can get the type of the class.
# But it's too late, I would have liked
# to get it back in __call__.
return 10
class ClassA:
@MyCustomDescriptor(foo=1)
def some_value(self): pass
class ClassB:
@MyCustomDescriptor(foo=1)
def some_value(self): pass
The reason I’d like to get a reference to the class is that I’d like to add some static data to the class with the decorated function/method. I realize this is somewhat atypical but for what I’m doing, it would be helpful.
ANSWER – Can’t be done. Based on one of the responses below I inspected the stack from within call and was able to get the fully qualified class where the descriptor is being used (ClassA or ClassB in my example). But you can’t turn this into a type/class because the type/class is still being parsed (or whatever the right term is in python). In other words, python comes across ClassA and starts parsing it. While parsing it, it comes across the descriptor and invokes init and call on the descriptor. ClassA still hasn’t finished getting parsed. Therefore regardless of the fact that you can get a fully qualified module/class name from within call, you can’t turn it into a type.
At the point where the decorator is being applied,
some_valueis just a function, not a method. So, no, there is no way for the function to know it is associated with a particular class.Two alternatives are:
MyCustomDescriptor(along withfoo), orsome_value.The class decorator might look something like this:
For example, running
yields