Python:酸洗模块的替代方法 [英] Python: Alternatives to pickling a module

查看:87
本文介绍了Python:酸洗模块的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的程序 GarlicSim 上工作,用户可以在其中创建一个模拟,然后他可以进行操纵它可以按他的意愿保存,然后可以将其保存到文件中.

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.

我最近尝试实现保存功能.对我而言,自然发生的事就是腌制Project对象,该对象包含整个模拟.

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.

问题是,Project对象还包括一个模块-这就是模拟包",它是一个包/模块,其中包含几个定义模拟的关键对象(主要是函数).我需要将它们与仿真一起保存,但是似乎无法对模块进行酸洗,正如我在尝试对Project对象进行酸洗并引发异常时所见证的那样.

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.)

推荐答案

如果项目以某种方式引用了您需要的东西的模块,听起来您可能希望将该模块的使用重构为模块.无论如何,这通常会更好,因为使用模块来解决全球范围内的巨大肥胖问题.以我的经验,这样的应用程序结构只会导致麻烦.

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.

(当然,快速的解决方法是保存模块的 dict 而不是模块本身.)

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

这篇关于Python:酸洗模块的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆