[Python-ideas] Add a way to test for a descriptor in Python Code
Steven D'Aprano
steve at pearwood.info
Tue Oct 30 06:30:31 EDT 2018
On Tue, Oct 30, 2018 at 04:40:40AM -0400, Joy Diamond wrote:
> """
> For classes, the machinery is in type.__getattribute__() which transforms
> B.x into B.__dict__['x'].__get__(None, B). In pure Python, it looks like:
>
> def __getattribute__(self, key):
> "Emulate type_getattro() in Objects/typeobject.c"
> v = object.__getattribute__(self, key)
> if hasattr(v, '__get__'):
> return v.__get__(None, self)
> return v
>
> """
[...]
> However, the call to `hasattr(v, '__get__')` appears to me to be incorrect.
I agree, but only because it fails to take into account that dunder
methods like __get__ are only looked up on the class, not the instance.
I believe a more accurate eumulation would be:
if hasattr(type(v), '__get__'):
return type(v).__get__(None, self)
Actually, on further investigation, I think it ought to be:
if inspect.hasattr_static(type(v), '__get__')
except that there is no hasattr_static, there's only a getattr_static.
So perhaps there ought to be a hasattr_static as well.
> The question is *NOT* whether 'v' has an attribute '__get__'; *BUT* whether
> `v` has a symbol `__get__` in any of the classes in it's method resolution
> order.
What's the difference as you see it?
--
Steve
More information about the Python-ideas
mailing list