[Python-Dev] __slots__ and default values

Kevin Jacobs jacobs@penguin.theopalgroup.com
Tue, 13 May 2003 10:07:45 -0400 (EDT)


On Tue, 13 May 2003, Raymond Hettinger wrote:
> Was there a reason that __slots__ makes initialized
> variables read-only?  It would be useful to have
> overridable default values (even if it entailed copying
> them into an instance's slots):
> 
> class Pane(object):
>     __slots__ = ('background', 'foreground', 'size', 'content')
>     background = 'black'
>     foreground = 'white'
>     size = (80, 25)
> 
> p = Pane()
> p.background = 'light blue'     # override the default
> assert p.foreground == 'white' # other defaults still in-place

Those attributes are read-only, because there is a name collision between
the slot descriptors for 'background' and 'foreground', so the class favors
the class variables.  Thus, no slots are allocated for 'background' and
'foreground', so the instance, not having an instance dictionary correctly
reports that those attributes are indeed read-only.

Also, slots are not automatically initialized from class variables, though
one can easily write a metaclass to do so.  (Actually, it is only easy for a
first approximation, it is actually quite tricky to get 100% correct.)

-Kevin

-- 
--
Kevin Jacobs
The OPAL Group - Enterprise Systems Architect
Voice: (216) 986-0710 x 19         E-mail: jacobs@theopalgroup.com
Fax:   (216) 986-0714              WWW:    http://www.theopalgroup.com