Per instance descriptors ?

Michael Spencer mahs at telcopartners.com
Wed Mar 22 16:34:11 EST 2006


Bruno Desthuilliers wrote:
> Michael Spencer a écrit :

>> I may be missing the subtlety of what you're up to, but why is 
>> overriding __getattribute__ more desirable than simply defining the 
>> descriptor in a  subclass?
> 
> The code snippet I gave as an example was not supposed to reflect how I 
> effectively mean to use per-instance descriptors, it was just a kind of 
> Minimal Working Code (tm). The real life code is about 500 LOC, and 
> explaining the whole thing would take far too long. Also, as I said, 
> this is mostly syntactic sugar - there are simpler, less 'hackish' (but 
> also less elegant) solutions to the actual 'problem'.So, to answer your
> question, no, subclassing would not be a solution - I'd almost need a 
> subclass per controller function, which would reintroduce the 
> boilerplate I'm trying to get rid of.
> 

> BTW, there may be other use case for per-instance descriptors... 

Agreed.  Per-instance descriptors could be interesting (that's why the subject 
line caught my attention).
But your solution involves a custom __getattribute__ in the class, which I would 
always avoid if possible (and I gather you're uneasy about it too).
Here, I don't see why that's better than having a descriptor in the class and, 
if it needs per-instance behavior, then make it dependent on something provided 
by the instance.

e.g.,
class DummyDescriptor1(object):
   def __get__(self, obj, objtype=None):
     if isinstance(obj, objtype):
         return obj.foo.__get__(obj)
     else:
         return self

class MyClass4(object):
   baaz = DummyDescriptor1()
   def __init__(self, foo, bar = None):
     self.foo = foo
     self.bar = bar

 >>> mc4 = MyClass4(lambda self: self.bar, "I'm bar")
 >>> mc4.baaz
 >>> mc4.baaz()
"I'm bar"
 >>> mc5 = MyClass4(lambda self: "I ignore bar", "I'm another bar")
 >>> mc5.baaz()
"I ignore bar"
 >>>


Python
> is so dynamic that you can almost use it like a prototype-based language.
> 
> 
Almost, yes.

Michael




More information about the Python-list mailing list