Automatic Generation of Python Class Files

Bruno Desthuilliers bruno.42.desthuilliers at
Tue Oct 23 09:37:40 CEST 2007

Steven Bethard a écrit :
> Bruno Desthuilliers wrote:
>> Steven Bethard a écrit :
>> (snip)
>>> In Python, you can use property() to make method calls look like 
>>> attribute access.  This could be necessary if you have an existing 
>>> API that used public attributes, but changes to your code require 
>>> those attributes to do additional calculations now.
>>> But if you're creating a class for the first time, it should *never* 
>>> use property().  There's no need to retrofit anything.
>> May I kindly disagree here ?-)
> Of course. ;-)
>> Computed attributes are IMHO not only a life-saver when it comes to 
>> refactoring. There are cases where you *really* have - by 'design' I'd 
>> say - the semantic of a property, but know from the start you'll need 
>> computation (for whatever reason). Then what would be the rationale 
>> for using explicit getters/setters ?
> I'd be interested to hear what these use cases are.

I once wrote a small ORM-like wrapper for LDAP access, and, for reasons 
that might be obvious for anyone having worked with LDAP, I choosed to 
keep the record values in the format used by the lower level LDAP lib 
and let user code access them thru computed attributes (actually 
custom-made descriptors). Talking about ORMs, most of them surely use a 
similar scheme.

I could also list the CS101 examples, like Shape.area, 
Rect.bottom_right, Person.age, etc... And yes, some of these attributes 
are obviously read-only. That doesn't prevent them from being 
semantically *properties*, not *behaviour*.

> Generally, people expect that attributes are used for simple state, and 
> methods are used when some sort of computation is required.
> If you use 
> attributes when some computation is required, you violate your users' 
> expectations.

Depends on which kind of people and on their background. I obviously 
don't advocate the use of computed attributes for heavy, non-cachable 
computations (please don't call me stupid !-), but not suffering from a 
too long exposures to some low-level mainstream languages, I never 
assume that attribute syntax implies direct attribute access.

> Of course, you can always document that your attributes require 
> computation. But you're definitely adding some cognitive load by 
> violating the normal expected behavior of attributes and methods.

"normal expected behaviour" ? "normal" according to which norm, and 
"expected" by who ? In a language with a very strong builtin support for 
computed attributes, the only thing to expect is that you don't have to 
call an attribute to get to the value.

More information about the Python-list mailing list