Self unpickling in class method in python

Iván Sánchez

I am trying to create an object which can serialize and deserialize itself with a class method, without using the return statement (I do not want a static method). This is a concept of my class and a naive use case:

import pickle

class A:
    def __init__(self):
        self.x = 0

    def add(self):
        self.x += 1

    def serialize(self, filename):
        """Simple object serialization given a filename"""
        with open(filename, 'wb') as f:
            pickle.dump(self, f)
            print("Serialized with value of: %d" % (self.x))

    def deserialize(self, filename):
        """Simple object deserialization given a filename"""
        with open(filename, 'rb') as f:
            print("self.x before load (inside deserialize): %d" % (self.x))
            self = pickle.load(f)
            print("Deserialized value inside deserialize function: %d" % (self.x))



a1 = A()
a2 = A()

a1.add()
a1.add()

a1.serialize('a.pkl')
a2.deserialize('a.pkl')

print("Deserialized value outside: %d" % (a2.x))

However, once I leave the deserialization method, self (in this case, the instance a2) does not keep its value.

Output when run:

>> Serialized with value of: 2
>> self.x before load (inside deserialize): 0
>> Deserialized value inside deserialize function: 2
>> Deserialized value outside: 0

Why is this happening? I have also tried with deepcopy just after the pickle.load in the function deserialize but nothing seems to work, and I would like to understand why.

Thanks in advance

L3viathan

The reason this doesn't work is that because you can't assign to self (or rather: doing that doesn't do what you think it does). If you're interested to find out what actually happens, try assigning something weird to self, e.g. self = "foobar" (the behaviour will be unchanged).


Make deserialize a classmethod and use it as a "constructor":

@classmethod
def deserialize(cls, filename):
    """Simple object deserialization given a filename"""
    with open(filename, 'rb') as f:
        obj = pickle.load(f)
        print("Deserialized value inside deserialize function: %d" % (obj.x))
        return obj

Then use it like this:

a2 = A.deserialize('a.pkl')

Output:

Serialized with value of: 2
Deserialized value inside deserialize function: 2
Deserialized value outside: 2

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Self is not passed to the class method in Python

Python class with static method and reference to self

No self parameter passed in overrided python class' method

Unpickling "None" object in Python

Python unpickling stack underflow

Python annotation error when a method of a class get as input the class it self

What is self in Python? If a second class is inheriting another class and its method, what do the 'self's indicate?

Create method with class self variables outside of a python class and then add it as a method to class

python: is it legal to pass self to the nested function inside the class method?

Python self.attribute cannot be seen when calling class method

can I bypass passing self object to a python class method?

Python - default value in class method and <code>self</code>

Python class: passing in self.var as a method argument yields no assignment?

Python method where first argument is either class or self

Using a Python method from another class without self

use current class without self in python (static method inherit)

Why class method must have self parameter in python?

How to run self referenced method from dictionary in python class?

self.variable.function() meaning in python or accessing a method through a class self variable

Class method decorator with self arguments?

Class method decorator with self arguments?

Class method: 'self' not being read

self is not defined in class method argument

Python Class: overwrite `self`

Unpickling a python 2 object with python 3

How can I return self and another variable in a python class method while method chaining?

Class Method Swapping Keeping Old Class 'Self'?

Python 3.9: unpickling of IsoCalendarDate data returns a tuple

unpickling in w+b mode in python