[Python-Dev] __slots__ and default values

Delaney, Timothy C (Timothy) tdelaney@avaya.com
Wed, 14 May 2003 07:32:49 +1000


> From: Raymond Hettinger [mailto:raymond.hettinger@verizon.net]
>=20
> class Pane(object):
>     __slots__ =3D ('background', 'foreground', 'size', 'content')
>     background =3D 'black'
>     foreground =3D 'white'
>     size =3D (80, 25)
>=20
> p =3D Pane()
> p.background =3D 'light blue'     # override the default
> assert p.foreground =3D=3D 'white' # other defaults still in-place

Wow - I hadn't realised that.

I would prefer to think of this is a useful feature rather than a wart. =
Finally we can have true constants!

class Pane (module): # Or whatever - you get the idea ;)

    __slots__ =3D ('background', 'foreground', 'size', 'content', =
'__name__', '__file__')
    __name__ =3D globals()['__name__']
    __file__ =3D globals()['__file__']

    background =3D 'black'
    foreground =3D 'white'
    size =3D (80, 25)

import sys
sys.modules[__name__] =3D Pane()

OK - so you could get around it by getting the class of the "module" and =
then modifying that ... but it's the best yet. It even tells you that =
the attribute is read-only!

Tim Delaney