Per instance descriptors ?

bruno at modulix onurb at xiludom.gro
Wed Mar 22 10:38:49 EST 2006


Ziga Seilnacht wrote:
> bruno at modulix wrote:
> 
>>Hi
>>
>>I'm currently playing with some (possibly weird...) code, and I'd have a
>>use for per-instance descriptors, ie (dummy code):
> 
> 
> <snip>
> 
>>Now the question: is there any obvious (or non-obvious) drawback with
>>this approach ?
> 
> 
> Staticmethods won't work anymore:
> 
> 
>>>>class Test(object):
> 
> ...     @staticmethod
> ...     def foo():
> ...         pass
> ...     def __getattribute__(self, name):
> ...         v = object.__getattribute__(self, name)
> ...         if hasattr(v, '__get__'):
> ...             return v.__get__(self, self.__class__)
> ...         return v
> ...
> 
>>>>test = Test()
>>>>test.foo()
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: foo() takes no arguments (1 given)
> 

Hmmm.... Well, I almost never use staticmethods, but I need to check
this out.

(a few minutes later)

Ok, no apparent impact on classmethods. For staticmethod, a quick fix is:

import types

> ...     def __getattribute__(self, name):
> ...         v = object.__getattribute__(self, name)
> ...         if not isinstance(v, types.FunctionType) \
                and hasattr(v, '__get__'):
> ...             return v.__get__(self, self.__class__)
> ...         return v


Thanks Ziga.


Anyone else ? Any good reason to *not* do this ? Or is presumably safe ?
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list