Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pattern for sharing configuration throughout application

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

like image 562
aaa90210 Avatar asked Apr 19 '11 01:04

aaa90210


People also ask

What is config () in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.

HOW include config file in Python?

Python can have config files with all settings needed by the application dynamically or periodically. Python config files have the extension as . ini. We'll use VS Code (Visual Studio Code) to create a main method that uses config file to read the configurations and then print on the console.

What is INI file in Python?

An INI file is a configuration file for computer software. It contains key-value pairs that represent properties and their values. These key-value pairs are organized under sections.


2 Answers

You could just:

import config 

and have a global config module


excerpts from my comments:

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

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.

like image 91
ninjagecko Avatar answered Oct 03 '22 07:10

ninjagecko


Answering old question:

Just use dependency injection as suggested by @Reed Copsey here. E.g.

class MyClass:     def __init__(myConfig):         self.myConfig = myConfig         ...      def foo():         self.myConfig.getConfig(key)         ...         self.myConfig.setConfig(key,val)         ...  ... # myConfig is your configuration management Module/Class obj = SomeClass(myConfig) 
like image 40
Basel Shishani Avatar answered Oct 03 '22 08:10

Basel Shishani