Skip to main content

Config files in Python projects

This document would serve as a part of the standard GQC Dev practices in Python projects involving a configuration file.

Dont's

  1. Instead of defining all constants and configuration variables in settings.py or constants.py, we would define those constants inside a TOML file.

Do's

  1. Python 3.11 comes with tomllib installed as a part of the Python Language
  2. For version 3.8 to 3.10, we would download toml lib manually, pip install toml

toml file

This is a sample toml document.

foo.toml
# This is a TOML document.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # First class dates

[database]
server = "192.168.1.1"
ports = [ 8000, 8001, 8002 ]
connection_max = 5000
enabled = true

To read the file

import toml
data = toml.load("foo.toml")
  • Earlier versions of python have a built-in configparser library for ini files.
  • People in the online community say that toml is more powerful and robust compared to ini files.