Pickle load `__dict__` doesn't load all attributes

Viewed 71

Question

I'm trying to save a class Level to file. But my recently added attribute particle is not included when I run the following minimal test case (python 3.7). It crashes on the last line. Why is it not included when pickling?

Short explaination of code

The Vector3d class inherits numpy.ndarray and then Particle inherits Vector3d with an added attribute particle. Level then contains a list containing a Particle. This particle contains the attribute before saving since the first print statement works, but the second doesn't.

import numpy as np
import pickle

class Vector3d(np.ndarray):

    def __new__(cls, x, y, z):
        self = np.asarray([x,y,z], dtype=int).view(cls)
        return self

class Particle(Vector3d):

    def __new__(cls, particle: int, x: int, y: int, z: int):
        self = Vector3d.__new__(cls, x, y, z)
        self.particle = particle

        return self

class Level:
    def __init__(self):
        self.particles = [
            Particle(42, 1, 2, 3)
        ]

    def save(self):
        save_file = open("tmp.level", 'wb')
        pickle.dump(self.__dict__, save_file)
        save_file.close()

    def load(self):

        with open("tmp.level", 'rb') as load_file:
            loaded_level = pickle.load(load_file)

            self.__dict__ = loaded_level

if __name__ == "__main__":
    level = Level()
    level.save()

    saved_level = Level()
    saved_level.load()

    print(f"original particle = {level.particles[0].particle}")
    print(f"loaded particle = {saved_level.particles[0].particle}")
0 Answers
Related