Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing settings\constants between Python projects

What would be a neat way to share configuration parameters\settings\constants between various projects in Python?

Using a DB seems like an overkill. Using a file raises the question of which project should host the file in its source control...

I'm open for suggestions :)

UPDATE:
For clarification - assume the various projects are deployed differently on different systems. In some cases in different directories, in other cases some of the projects are there and some are not.

like image 632
Jonathan Livni Avatar asked Mar 12 '26 11:03

Jonathan Livni


2 Answers

I find that in many cases, using a configuration file is really worth the (minor) hassle. The builtin ConfigParser module is very handy, especially the fact that it's really easy to parse multiple files and let the module merge them together, with values in files parsed later overriding values from files parsed earlier. This allows for easy use of a global file (e.g. /etc/yoursoftware/main.ini) and a per-user file (~/.yoursoftware/main.ini).

Each of your projects would then open the config file and read values from it.

Here's a small code example:

basefile.ini:

[sect1]
value1=1
value2=2

overridingfile.ini:

[sect1]
value1=3

configread.py:

#!/usr/bin/env python

from ConfigParser import ConfigParser

config = ConfigParser()
config.read(["basefile.ini", "overridingfile.ini"])

print config.get("sect1", "value1")
print config.get("sect1", "value2")

Running this would print out:

3
2
like image 112
Erik Forsberg Avatar answered Mar 14 '26 01:03

Erik Forsberg


Why don't you just have a file named constants.py and just have CONSTANT = value

like image 29
Pwnna Avatar answered Mar 14 '26 00:03

Pwnna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!