tags:

views:

19

answers:

1

I am doing deepcopy on a class I designed, which has multiple lists as attributes to it. With a single list, this is solvable by overriding getstate to return that list, and setstate to set that list, but setstate seems unable to take multiple parameters.

How is this accomplished?

A: 

You can have __getstate__ return (and __setstate__ accept) a list of lists, or a dict (if you implement __getstate__ and __setstate__, __getstate__ doesn't have to return a dict)

import pickle

class Example:
    def __init__(self):
        self.list1 = [1]
        self.list2 = [2]

    def __getstate__(self):
        return {'list1': self.list1, 'list2': self.list2}

    def __setstate__(self, state):
        self.list1 = state['list1']
        self.list2 = state['list2']

ex = Example()
s = pickle.dumps(ex)
ex2 = pickle.loads(s)
print ex.list1, ex.list2

This is just a demo. You really don't even need to override pickle's default behavior for a simple case like this.

Matthew Flaschen
Ah, awesome! Didn't know you could lay out the getstate like that. Thanks a ton
coffee