IOMixin¶
A mixin class that adds to_file() and from_file() methods to any class, backed by DataZip.
datazip.mixin.IOMixin ¶
Mixin for adding DataZip IO.
Examples:
Create a class that inherits from IOMixin.
Create an instance of the class with many kinds of things in it. As nested as you like.
>>> inst = MyClass()
>>> inst.foo = {"a": 1, "b": (1, 2, 3), "c": [1, 2, 4]}
>>> inst.bar = [1, 2, 3]
The object can now be saved to a file, or buffer for this example.
And we can bring it back, as if it was pickled. Usually.
If your class has funny things in it like lambdas or unserializable objects,
you will need to define __getstate__ and __setstate__. If you don't use
__slots__ they can be very simple.
>>> from collections import defaultdict
>>> class MyFunnyClass(IOMixin):
... def __init__(self):
... self.stuff = defaultdict(lambda: None)
...
... def __getstate__(self):
... return self.__dict__ | {"stuff": dict(self.__dict__["stuff"])}
...
... def __setstate__(self, state):
... self.__dict__ = state | {
... "stuff": defaultdict(lambda: None, state["stuff"])
... }
Instantiate the class and use defaultdict.
Dump the object into the buffer and delete the original instance.
Recreate the object from the buffer and confirm it is as it should be.