Adding properties to an instance

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Feb 7 06:58:46 EST 2008


dg.google.groups at thesamovar.net a écrit :
>> As a side note: the naming symetry between __getattr__ and __setattr__
>> is a gotcha, since __setattr__ is mostly symetric to __getattribute__ -
>> IOW, customizing __setattr__ is a bit tricky. The naive approach, ie:
> 
> Ah I see - so __setattr__ is called immediately whereas __getattr__ is
> only called if the other methods fail. 

Yes.

> Does this mean that __setattr__
> incurs the same performance penalty that overriding __getattribute__
> would? 

Not quite AFAICT - there's less going on here. Also, getting an 
attribute is (usually at least) more common than setting it.

> Possibly I can live with this because I think that most of what
> I'm doing is getting attributes, or modifying mutable ones, rather
> than setting them.

Well... Using the __setattr__/__getattr__ hooks is IMHO the simplest 
solution that can possibly work - far simpler than your previous one at 
least. As far as I'm concerned, and unless some other point of your 
specs make this unusable or unpractical, I'd go for this solution first 
and run a couple benchs on real-life-or-close-to conditions to check if 
the performance hit is acceptable.




More information about the Python-list mailing list