Python3, __slots__ and serialization
ned at nedbatchelder.com
Sat Feb 8 19:29:34 CET 2014
On 2/8/14 1:06 PM, Eric Jacoboni wrote:
> Say i want create a class with a __slots__ tuple in order to prevent
> creation of new attributes from outside the class.
> Say i want to serialize instances of this class... With pickle, all is
> ok : i can dump an object to a file, then reload it.
> With PyYAML, i can dump an object to a file, but trying to reload it fails.
> If i comment out the __slots__ tuple, all is fine but, then, the class
> is "open"... Is there some magic to have both a __slots__ tuple and a
> working yaml.load() ?
Preventing attribute creation runs counter to Python's philosophy, so it
doesn't surprise me that it causes problems. There might be a way to
make it all work together, but I don't know.
__slots__ wasn't meant to be a way to prevent attribute creation, it was
meant as a way to save space by avoiding the need for an attributes
Why do you need to prevent attribute creation? If someone uses your
class and wants to use it in ways you didn't anticipate, why should you
try to stop them?
Ned Batchelder, http://nedbatchelder.com
More information about the Python-list