In Python, the __dict__
of an instance seems to be "open" for some classes, "closed" for others:
# "closed" type example:
x = object()
x.eggs = 'spam' # raises an AttributeError
whereas:
# "open" type example I:
x = Exception()
x.eggs = 'spam' # does not raise an AttributeError
# "open" type example II: subclasses
class thing(object): pass
x = thing()
x.eggs = 'spam' # does not raise an AttributeError
I would like to understand where/how/why this difference in behaviour is implemented: why is object
closed but thing
open? Why is Exception
open? I have two reasons for the question:
In pure Python, the only way I have found of replicating the "closed" behaviour is to implement
__setattr__
myself and raise theAttributeError
in it, composing its appropriately-formatted error message by hand. Is there a less-verbose, more-DRY way (and one which doesn't generate a potentially misleading backtrace to__setattr__
)?In an IPC module I have written, I want to document an example of usage, and the most concise and universal way would be to find an example of a builtin
type
(failing that, one from the standard library) (a) which can be pickled and sent to another process, and (b) whose instances exhibit the "open" behaviour. So far the best one I have found isException
but that looks a little misleading in the documentation (people will think it's specifically about exceptions). A more generic object would be nicer, butobject
is closed, and a subclass (likething
in the example above) is notpickle
able unless you save its definition in a file on the path. Maybe there's a standard container somewhere that's open? The classics (tuple/list/dict
) are all closed.