C-style static variables in Python?
Stephen Hansen
apt.shansen at gmail.invalid
Sat Apr 3 15:03:59 EDT 2010
On 2010-04-02 20:24:46 -0700, Patrick Maupin said:
> 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.
I concede it would probably be notably faster, but there's a big
difference between "at all concerned about speed" and "optimizing a
profiled bottleneck".
The speed difference between direct attribute lookup and properties may
be notable, but that doesn't make a clear winner here. Now that I have
(with either method) optimized the expensive value-calculation
operation such that it only happens on-demand and once, I now have to
weigh further optimization.
Is the difference in speed between a standard attribute lookup and a
property fetch worth losing the clarity the property brings over the
__getattr__ solution, especially considering the __getattr__ creates a
fuzzy 'sometimes this code is responsible, othertimes the dict is'
situation that someone may down the road miss in maintenance?
For me, usually not-- unless profiling pushes me to reconsider. But
everyone makes these calls differently.
> 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.
I don't really mind a lot of properties, if they're simple. Then again,
I often prefer regular ol' attributes where possible :) However, if I'm
doing a dispatching sort of mechanism, or a situation where the "name"
isn't something static, set in stone or pre-defined-- then certainly,
__getattr__ is a fine solution. I don't mind it where its the clearest
way to accomplish a goal.
--
--S
... p.s: change the ".invalid" to ".com" in email address to reply privately.
More information about the Python-list
mailing list