Exclude object's field from pickling in python

后端 未结 3 1924
情歌与酒
情歌与酒 2020-12-29 03:06

I would like to avoid pickling of certain fields in an instance of a class. Currently, before pickling I just set those fields to None, but I wonder whether there\'s more el

3条回答
  •  感动是毒
    2020-12-29 03:55

    Pickling uses the object's __getstate__ and __setstate__ methods; you can override them and ignore the fields you want.

    # foo.py
    class Foo:
        def __init__(self):
            self.bar = 1
            self.baz = 2
    
        def __getstate__(self):
            state = self.__dict__.copy()
            # Don't pickle baz
            del state["baz"]
            return state
    
        def __setstate__(self, state):
            self.__dict__.update(state)
            # Add baz back since it doesn't exist in the pickle
            self.baz = 0
    
    # main.py
    import pickle
    
    from foo import Foo
    
    
    foo = Foo()
    print(f"Foo bar: {foo.bar} baz: {foo.baz}")
    
    new_foo = pickle.loads(pickle.dumps(foo))
    print(f"New bar: {new_foo.bar} baz: {new_foo.baz}")
    

    Output:

    Foo bar: 1 baz: 2
    New bar: 1 baz: 0
    

    You can find another example here: https://docs.python.org/3/library/pickle.html#handling-stateful-objects

提交回复
热议问题