1
votes

I am interested in saving and load objects using the pickle module as you can read in a question I asked before: Python: Errors saving and loading objects with pickle module

Someone commment:

1, In an other way: the error is raise because pickle wanted to load an instance of the class Fruits and search for the class definition where it was defined, but it didn't find it so it raise the error

Now I want to save and load a class definition in order to solve the problem I describe in the question mentioned before. Thank you so much!

1
If you really mean "save and load the class definition", that's what python source files are for... - Andrew Jaffe
Could you please explain why you want to do that? - Keith
Why not just import the class, separate from the loading the pickled objects? What's wrong with a simple import? - S.Lott
Putting the class(es) in a separate file and import ing them is also what I suggested following your similar last comment/question to my answer to your question Python: saving and loading objects and using pickle.. - martineau

1 Answers

9
votes

The pickle module saves and loads the objects internal state. The code is not a part of the internal state, not even for classes, so therefore it gets tricky.

The obvious way is to make the whole class definition in a string, pickle that string, and then load it, and exec() that string. Another option that may or may not work is to have a metaclass that can pickle and unpickle the code as well, but that is way more difficult, and not really any better.

This is however an extremely bad idea for tons of reasons, and I would bet a significant amount of my reputation point on that you have no good reason to do that. You are with 99.9% likelihood barking up the wrong tree. You are trying to solve a problem you have because you have chosen the wrong solution to do something, and now you are trying to solve the problems that solution is giving you, instead of choosing a better solution that likely will be very simple to implement.

So you need to not only explain the current problem you have, but also the large scale usecase you are trying to solve. We can then tell you how to solve that usecase in a better way.