python - pickle port? loading a pickle with data when I've redefined the object code - Stack Overflow

时间: 2025-01-06 admin 业界

I've been building "company files" which contain lots of data for specific companies. I then pickle these and keep moving so I can work on one at a time.

As I'm going, I keep adding methods and relative attributes to my working classes. But then when I import from these company objects I get AttributeError.

class Company(object):
    def __init__(self):
        self._obj_ver = 1.0

Then I do some work and save:

in: company = Company()
### do stuff
in: with open(pkl_co_1, 'wb') as f:
        pickle.dump(company, f, pickle.HIGHEST_PROTOCOL)

I added some functionality and stuff while working on company 2+, and added an observer pattern to make data updates faster:

class Company(object, Observable): #<== notice the new inheritance, so great, until it's not
    def __init__(self):
        self._obj_ver = 2.0

So obviously, when I go back to company 1 my objects are missing some stuff:

#read the pickle file
with open(pkl_co_1, 'rb') as f:
    company = pickle.load(f)

try stuff:

in: company._obj_ver
out: 1.0 #<== even though the code __init__ is now 2.0... it's why I have this attribute
in: company.observers #Attribute from Observable class, which only exists in obj_ver 2.0+
out: kablooey!!!

This is all expected behavior at this point. So here's what I'm wondering. Is there a toolset or has someone done a "Port pickle"?

I'm thinking it's some sort of: pickle_port_magician.py

def port(company_v1_obj, newco):
    for item in company_v1_obj.__dict__:
        newco.getattr(self, item) = company_v1_obj.getattr(copmany_v1_obj?, item)

I'm just really fuzzy on what object I should be using, and I feel like I can't be the only one who's had this issue.

Does anyone have a way to port pickles from an older version of the object definition to a new version of the object definition?

Python 3.12.2