0

So, I am pickling an object from within the class ( see How to pickle yourself ) :

    def save(self, path):
        f = open(path, 'wb')
        pickle.dump(self, f)
        f.close()


    @classmethod
    def load(cls, path):
        f = open(path, 'rb')
        obj = pickle.load(f)
        f.close()
        return obj

which works fine. But there is one large attribute I don't want to pickle in most cases. How can I do that? Should look somehow like this:

        def save(self, path, without_attr_x =True):
            f = open(path, 'wb')
            if(without_attr_x):
                #somehow remove attr_x from the pickling
                # I could do self.attr_x = None but this deletes attr_x from the running instance as well
            pickle.dump(self, f)
            f.close()
chefhose
  • 2,399
  • 1
  • 21
  • 32
  • you would have to remove this attribute from class/instance before pickling. You can assing it to external variable, delete it in class/instance, pickle class/instance, and assign again from external variable. – furas Oct 08 '20 at 10:07
  • @furas simple and easy - this should probably be an answer – chefhose Oct 09 '20 at 13:03

1 Answers1

1

You would have to remove this attribute from class/instance before pickling.

You can assing it to external/global variable, delete it in class/instance, pickle class/instance, and assign again from external/global variable.

Something like this:

# ... external variables ...

attr_x = None

# ... class ...

def save(self, path, without_attr_x=True):
    global attr_x
    
    f = open(path, 'wb')
    
    if without_attr_x:
        # assign to external variable
        attr_x = self.attr_x
        # remove value
        self.attr_x = None
        
    pickle.dump(self, f)

    if without_attr_x:
        # assign back from external variable
        self.attr_x = attr_x

    f.close()
furas
  • 134,197
  • 12
  • 106
  • 148