用于在应用程序间共享配置的Python模式 [英] Python pattern for sharing configuration throughout application
问题描述
我有一个应用程序,包含一个基本的应用程序,带来了几个模块。基本应用程序将参数文件读入配置哈希,我想在所有模块中共享它。
目前,我传递一个父对象到模块,然后那些模块正在做类似self.parent.config的东西,以获取配置。
然而,由于模块层次结构有几个层次,我发现自己做的事情像self.parent.parent.config,这开始看起来不好。
有什么更好的模式共享一个应用程序的配置对象,它的模块?我正在考虑有一个'config'模块,基本上创建一个全局配置变量,可以由基本应用程序设置,然后导入和访问其他模块,但我不知道如果使用这样的全局变量是一个糟糕的做法,其他
您可以:
import config
并拥有全局配置模块
/ p>
如果isOddSituation()else config.normalValue ,你总是可以通过 如果你想要配置模块是层次化的子类(像我的其他答案所描述的),那么你可以表示一个配置类,或者你可以使用 这真的不是太重要的范围。 I have an application consisting of a base app that brings in several modules. The base app reads a parameter file into a configuration hash, and I want to share it across all my modules. Currently, I am passing a 'parent' object down to modules, and then those modules are doing stuff like self.parent.config to obtain the configuration. However, as there are several levels to the module hierarchy, I find myself doing things like self.parent.parent.config, which is starting to look bad. What are some better patterns for sharing a config object across an application and it's modules? I am thinking about having a 'config' module which basically creates a global config variable that can be set by the base app, then imported and accessed by other modules, but I am not sure if using globals like that is a bad practice for other reasons. I am reasonably new to Python so be nice =) You could just: and have a global config module excerpts from my comments: You can always add special rules for odd situations by just saying If you want to have configuration modules be hierarchically subclassable (like my other answer describes), then you can represent a config as a class, or you can use the It doesn't really matter too much which scope you're in. 这篇关于用于在应用程序间共享配置的Python模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! oddValue添加奇怪情况的特殊规则。 / p>
copy
模块并进行浅拷贝并修改它,或者您可以使用配置字典,例如:
import config as baseConfig
config = dict(baseConfig,overriddenValue = etc)
$ b b import config
oddValue if isOddSituation() else config.normalValue
.copy
module and make a shallow copy and modify it, or you can use a "config dictionary", e.g.:import config as baseConfig
config = dict(baseConfig, overriddenValue=etc)