简体   繁体   中英

Manually editing a dumped pickle file in python

I have two classes ClassA and ClassB with the same content and structure but just with different names. I saved an object of ClassA using pickle.dump to a binary file. However, I want to now load it in a different program which only has access to ClassB . Loading this file using pickle.load fails now as it can't find the ClassA description and thus throws some error like No module named ClassA exists .

To solve this, I manually investigated the saved binary file, and found the required class name ClassA coded in ASCII in the file. I guessed that it was looking for this exact class name, which resulted in the above error. Upon changing this name from ClassA to ClassB inside this binary file, the code seemed to be correctly loading the object, but now as ClassB . Which is what i wanted.

However, since i manually edited this file, I was wondering if there would be any adverse effects down the line for doing this. Or is it, if it works it ain't stupid scenario.

Thanks in advance.

None of the pickle formats use offsets into the file or any kind of compression or encryption, so changing the name is fine even if it changes the length. You have to know that the text “ClassA” doesn't appear for some other reason, of course, and that your editor won't mangle the file—say, by trying to do character decoding/encoding.

That said, in this situation I'd probably create a dummy package to give ClassA the correct name rather than edit the pickle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM