RE: [Python-Dev] __slots__ and default values

From: Raymond Hettinger [mailto:raymond.hettinger@verizon.net]
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
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__ = ('background', 'foreground', 'size', 'content', '__name__', '__file__') __name__ = globals()['__name__'] __file__ = globals()['__file__'] background = 'black' foreground = 'white' size = (80, 25) import sys sys.modules[__name__] = 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

I would prefer to think of this is a useful feature rather than a wart. Finally we can have true constants!
Yuck. If you want that, define a property-like class that doesn't allow setting. These "constants" of yours are easily subverted by defining a subclass which adds an instance __dict__ (any subclass that doesn't define __slots__ of its own does this). --Guido van Rossum (home page: http://www.python.org/~guido/)
participants (2)
-
Delaney, Timothy C (Timothy)
-
Guido van Rossum