开发者

Python: saving and loading a class definition

开发者 https://www.devze.com 2023-02-02 14:10 出处:网络
I am interested in saving and load object开发者_JAVA百科s using the pickle module as you can read in a question I asked before:

I am interested in saving and load object开发者_JAVA百科s 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消