Best way to add attributes to shelved objects?

Skip Montanaro skip at pobox.com
Mon Apr 26 11:48:33 EDT 2004


    skip> Why not check for those attributes in your __getstate__ method and
    skip> add default (or computed) values for any missing attributes?

    jm> I tried experimenting with these, and could not get them to work.
    ...
    jm> Are there any examples on how to do this?

How about:

    class Foo:
        def __init__(self):
            self.a = 1

        def __setstate__(self, d):
            if 'b' not in d:
                d['b'] = 2
            self.__dict__ = d

    f = Foo()
    print hasattr(f, "a"), hasattr(f, "b")

    import pickle
    pfile = file("test.pck", "wb")
    pickle.dump(f, pfile)
    pfile.close()

    f = pickle.load(file("test.pck", "rb"))
    print hasattr(f, "a"), hasattr(f, "b")

Skip




More information about the Python-list mailing list