wg4568 wg4568 - 1 month ago 23
Python Question

Best practice for config variables in Python

So recently my programs have become more complex, and are starting to require more configuration. I've been doing the following, however it feels wrong...

class config:
delay = 1.3
files = "path/to/stuff"
name = "test"

dostuff(config.name) #etc...


I've never been a fan of the ALL_CAPS_VARIABLE method, and was wondering if there is an "official" way to do this, and if there is anything wrong with my current method.

Answer

I recommend use of python-decouple. This library allow separate code from configurations(data).

UPDATE:

Brief explanation of usage of this library:

Simply create a .env text file on your repository's root directory in the form:

DEBUG=True
TEMPLATE_DEBUG=True
EMAIL_PORT=405
SECRET_KEY=ARANDOMSECRETKEY
DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase
PERCENTILE=90%
#COMMENTED=42

On your python code, can be used in this way:

from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)