用于在整个应用程序中共享配置的 Python 模式 [英] Python pattern for sharing configuration throughout application

查看:31
本文介绍了用于在整个应用程序中共享配置的 Python 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中包含一个包含多个模块的基本应用程序.基础应用程序将参数文件读取到配置哈希中,我想在我的所有模块中共享它.

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.

目前,我正在将一个父"对象传递给模块,然后这些模块正在执行诸如 self.parent.config 之类的操作来获取配置.

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.

但是,由于模块层次结构有多个级别,我发现自己在做诸如 self.parent.parent.config 之类的事情,这开始看起来很糟糕.

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.

我对 Python 还算陌生,所以请保持友善 =)

I am reasonably new to Python so be nice =)

推荐答案

你可以:

import config

并有一个全局配置模块

摘自我的评论:

你总是可以通过说oddValue if isOddSituation() else config.normalValue来为奇怪的情况添加特殊规则.

You can always add special rules for odd situations by just saying oddValue if isOddSituation() else config.normalValue.

如果您希望配置模块可以分层子类化(就像我的其他答案所描述的那样),那么您可以将配置表示为一个类,或者您可以使用 copy 模块并制作一个浅拷贝并修改它,或者您可以使用配置字典",例如:

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

你在哪个范围内并不重要.

It doesn't really matter too much which scope you're in.

这篇关于用于在整个应用程序中共享配置的 Python 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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