[PYTHON] Test methods for customizing Pickle behavior

pickle is a standard library for serializing Python objects into bytes for saving to files etc. Pickable objects are pickable, and recreating an object from a serialized byte sequence is called Unpickle.

By default Pickle tries to serialize the attributes of objects registered in __dict__, but you can customize its behavior by defining a special method for pickle. Especially, it is used when the object to be pickled has an object that cannot be pickled as a member, or when the object is created by a constructor that takes an argument.

Method Intended use
__getnewargs__() Specify the argument to be passed to the constructor when unpickling.
__getstate__() __dict__Instead, pickle the object returned by this method.
__setstate__(state) Receives the pickled object as a state and performs the processing at the time of unpickle.

The following code is a sample script to see the behavior of these methods.

python


import pickle

class Foo:
    def __new__(self, a):
        print('in __new__:', a)
        self = object.__new__(self)
        # self.a = a
        return self
    
    def __init__(self, a):
        print('in __init__:', a)
        self.a = a

    def __getstate__(self):
        print('in __getstate__:', self.a)
        state = self.__dict__.copy()
        return state

    def __getnewargs__(self):
        print('in __getnewargs__:', self.a)
        return (2 * self.a,)

    def __setstate__(self, state):
        self.__dict__.update(state)
        print('in __setstate__:', self.a)


foo = Foo(3)
bar = pickle.dumps(foo)
baz = pickle.loads(bar)
print(baz.__dict__)

The result of executing this script is as follows.

python


in __new__: 3
in __init__: 3
in __getnewargs__: 3
in __getstate__: 3
in __new__: 6
in __setstate__: 3
{'a': 3}

As stated in the pickle manual, you can see the following.

--__getnewargs__ is called when pickling. In other words, the argument information passed to __new__ when unpickled is pickled. --The value returned by __getnewargs__ is passed to __new__. --Unpicle does not call __init__.

Recommended Posts

Test methods for customizing Pickle behavior
Test automation for work
Hypothesis test for product improvement
For the G test 2020 # 2 exam
Test code for evaluating decorators
Python template for Codeforces-manual test-