Python: Alternatives to pickling a module

2019-02-18 16:02发布

I am working on my program, GarlicSim, in which a user creates a simulation, then he is able to manipulate it as he desires, and then he can save it to file.

I recently tried implementing the saving feature. The natural thing that occured to me is to pickle the Project object, which contains the entire simulation.

Problem is, the Project object also includes a module-- That is the "simulation package", which is a package/module that contains several critical objects, mostly functions, that define the simulation. I need to save them together with the simulation, but it seems that it is impossible to pickle a module, as I witnessed when I tried to pickle the Project object and an exception was raised.

What would be a good way to work around that limitation?

(I should also note that the simulation package gets imported dynamically in the program.)

2条回答
啃猪蹄的小仙女
2楼-- · 2019-02-18 16:40

If the project somehow has a reference to a module with stuff you need, it sounds like you might want to refactor the use of that module into a class within the module. This is often better anyway, because the use of a module for stuff smells of a big fat global. In my experience, such an application structure will only lead to trouble.

(Of course the quick way out is to save the module's dict instead of the module itself.)

查看更多
Lonely孤独者°
3楼-- · 2019-02-18 16:56

If you have the original code for the simulation package modules, which I presume are dynamically generated, then I would suggest serializing that and reconstructing the modules when loaded. You would do this in the Project.__getstate__() and Project.__setstate__() methods.

查看更多
登录 后发表回答