Per instance descriptors ?

bruno at modulix onurb at xiludom.gro
Wed Mar 22 04:53:49 EST 2006


Hi

I'm currently playing with some (possibly weird...) code, and I'd have a
use for per-instance descriptors, ie (dummy code):

class DummyDescriptor(object):
  def __get__(self, obj, objtype=None):
    if obj is None:
      return self
    return getattr(obj, 'bar', 'no bar')

class MyClass1(object):
  def __init__(self, bar=None):
    if bar is not None:
      self.bar = bar
    self.baaz = DummyDescriptor()

mc1 = MyClass1(bar='back')
mc1.baaz
-> <__main__.DummyDescriptor object at 0x2aaaabc6c390>

Which is of course what one would expect...  Now I tried the following
hack^Mworkaround:

class MyClass2(MyClass1):
    def __getattribute__(self, key):
        v = MyClass1.__getattribute__(self, key)
        if hasattr(v, '__get__'):
            return v.__get__(self, self.__class__)
        return v

And it *seems* to work just fine:

mc2 = MyClass2(bar='foo')
mc2.baaz
->  'foo'

Now the question: is there any obvious (or non-obvious) drawback with
this approach ?

A bit of context:
1/ the real class is a decorator for controller functions in a
mod_python application, and given previous experiences with mod_python,
I'd prefer not mess with the class itself at runtime... still I'd like
to abstract some gory details, and descriptors would be an obvious
choice here.

2/ this is for production code, so robustness is more important than
syntactic sugar - but having this syntactic sugar would be nice...

Any hint ?

TIA
-- 
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