Bug or feature?

Tim Peters tim_one at email.msn.com
Sat May 15 14:11:40 EDT 1999


[about using class attrs to supply default values for instance attrs, and
 how that saves storage when many instances want the same value for a
 particular attr]

[Thomas A. Bryan]
> ...
> I've seen that idiom several times, but I never thought about why the
> author was using it.  I'll have to add that to my bag-of-tricks.

Do it with care, though -- it's not a pure win.  In return for saving
memory, attr access is slower (Python always looks in the instance dict
first!).  It's also arguably obscure, in that without a good comment you
really can't tell whether a class data attr is *intended* to be class data
or default instance data.

Something Michael was trying to get across appears to have gotten lost in
the shuffle:  this is the way, and the mechanism by means of which, *method*
invocation routinely works:  you do instance.method(args), and Python first
looks in instance's dict for "method".  It normally doesn't find anything
there, so moves up to the class dict.  So everyone uses this trick all the
time:  methods are the prototypical example of an attr for which all
instances want to see the same value.  The data-sharing "trick" is just
using the same mechanism for data attrs.

> Newsgroups are the most frequent cause of that
>  ah-ha-...-now-I-get-it feeling in my life.  Thanks, Tim.

Thomas, read a good book; hang out with a child; catch a fish & let it go.

when-i'm-on-my-deathbed-i'm-sure-i'll-look-back-and-wish-i'd-spent-
    more-time-on-c.l.py<wink>-ly y'rs  - tim






More information about the Python-list mailing list