[Tutor] Protected methods/variables
Kent Johnson
kent37 at tds.net
Wed Apr 5 14:15:33 CEST 2006
w chun wrote:
> On 4/4/06, Kent Johnson <kent37 at tds.net> wrote:
>> Mike Hansen wrote:
>>>>> - you can use __slots__ to restrict arbirtrary creation of
>>>> (dynamic)
>>>>> instrance attributes
>>>> You can do this, but it is generally considered a misuse of
>>>> __slots__ and potentially problematic.
>
> what specific problems were you thinking of? i would say that's it's
> clumsy to use during development because you're constantly changing
> __dict__ by adding new instance attributes, etc., so i only add a
> __slots__ when i'm finally done with the coding and want to prevent
> others from creating (dynamically) more instance attributes. it's too
> bad, because it sort goes against Zen#19 (namespaces are a honking
> good idea).
The main problem seems to be that it can be broken by inheritance. A
base or derived class can have a __dict__ which then allows additional
attributes to be added even if the derived or base class uses __slots__.
I admit to arguing from authority here but the consistent message on
c.l.py from those who should know is, don't use __slots__ to restrict
assignment, use __setattr__ instead; __slots__ should be used as a
memory optimization only. Search c.l.py for discussion.
>>> I'll bite. What is the proper/intended use of __slots__? Does it have
>>> something to do with memory?
>> Yes, it is intended specifically to reduce memory consumption of objects
>> that are going to be instantiated a lot. I'm not sure how many counts as
>> a lot, but in the thousands at least. Using __slots__ saves the cost of
>> the attribute dict for each instance.
>
> right, a class will either have __slots__ or __dict__ but not both.
As noted above, that is not necessarily true when inheritance is involved.
Kent
More information about the Tutor
mailing list