attributes, properties, and accessors -- philosophy

Ethan Furman ethan at stoneleaf.us
Tue Nov 24 15:59:15 EST 2009


Chris Rebert wrote:
> On Tue, Nov 24, 2009 at 9:39 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> 
>>Bruno Desthuilliers wrote:
>>
>>>Ethan Furman a écrit :
>>>
>>>>The problem I have with properties is my typing.  I'll end up assigning
>>>>to an attribute, but get the spelling slightly wrong (capitalized, or
>>>>missing an underscore -- non-obvious things when bug-hunting), so now I have
>>>>an extra attribute which of course has zero effect on what I'm trying to do
>>>>and I start getting wierd results like viewing deleted records when I *know*
>>>>I set useDeleted = False... 30 minutes later I notice it was /supposed/ to
>>>>be use_deleted.  *sigh*
>>>>
>>>>So -- to keep myself out of trouble -- I have started coding such things
>>>>as, for example:
>>>>
>>>>result = table.use_deleted()       # returns True or False
>>>>table.use_deleted(False)           # skip deleted records
>>>>
>>>>instead of
>>>>
>>>>result = table.use_deleted
>>>>table.use_deleted = False
>>>>
>>>>My question:  is this [ severely | mildly | not at all ] un-pythonic?
>>>
>>>
>>>Definitly and totally unpythonic. The first solution to your problem is to
>>>stick to standard naming conventions. If this is not enough, Chris pointed
>>>you to really useful tools. Also, you can override __setattr__ to catch such
>>>errors - at least during the coding/debug phase.
>>
>>Good tools to know about, and a consistent naming pattern also makes life
>>easier (which I have since done ;).
>>
>>Let's head towards murkier waters (at least murkier to me -- hopefully they
>>can be easily clarified):  some of the attributes are read-only, such as
>>record count; others are not directly exposed, but still settable, such as
>>table version; and still others require a small amount of processing... at
>>which point do I switch from simple attribute access to method access?
> 
> 
> Thanks to the magic of properties, the end-user-programmer need not
> know which you're using:
> 
> http://docs.python.org/library/functions.html#property

You know, when I first read that bit on properties a while back, the 
explanation of the decorators and how a property was also a decorator 
for the setter and deleter bits completely lost me.  Since then I've 
played with decorators a bit, written a configaration module that uses 
them, and just now, reading the description... it was so elegantly 
simple it almost brought tears to my eyes *sniff*.  I love Python.

Okay, I'll go back and switch all my attributes *back* to attributes -- 
and properties will be much nicer than my original implementation (using 
__getattr__ and __setattr__).

Many thanks to all who answered!

~Ethan~



More information about the Python-list mailing list