C-style static variables in Python?

Patrick Maupin pmaupin at gmail.com
Fri Apr 2 23:24:46 EDT 2010


On Apr 2, 10:11 pm, Stephen Hansen <apt.shan... at gmail.invalid> wrote:
>
> I don't know if properties are really faster or slower then a
> __getattr__, but I find them a lot cleaner if I want to delay some
> calculation until needed like that.

Well, the relative speed of properties vs. __getattr__ can become
irrelevant in at least two ways:

1) If the __getattr__ only calculates the value one time and then
stuffs it into the instance dictionary, now you are really comparing
the relative speed of properties vs. lookup of an attribute in the
instance dict.  If you're at all concerned about speed, I think there
is a clear winner here.

2) There is a single __getattr__ function, vs. one property for every
attribute that needs a property.  In cases where you can somehow
easily compute the attribute names as well as the attribute values,
__getattr__ can be a *lot* less code than defining dozens of
properties.

But you're absolutely right that, in many cases, property is the best
way to go for readability (especially if the property is read-only and
you're using a recent enough python to use decorators).

Regards,
Pat



More information about the Python-list mailing list