Skip to content

Configuration files

Most interesting programs need some kind of configuration. For very simple tasks you might choose to write these configuration variables directly into the source code. But this is a bad idea when you want to distribute your code and allow users to change configurations. Here are a few alternatives on how to handle configuration files in Python.

Using a .ini file *

Create a myfile.ini like:

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson

[Others]
barList=item1,item2

Retrieve the data like:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'

Using YAML *

YAML is a human friendly data serialization standard for all programming languages.

Create a config.yml file

database:
    username: admin
    password: foobar  # TODO get prod passwords out of config
    socket: /var/tmp/database.sock
    options: {use_utf8: true}
memcached:
    host: 10.0.0.99
workers:
  - host: 10.0.0.101
    port: 2301
  - host: 10.0.0.102
    port: 2302

Parse with:

import yaml
config = yaml.safe_load(open("config.yml"))

Using a Python module

Create a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

Use it like this:

import config
print(config.truck['color'])  

Other alternatives

  • Using a JSON file.
  • Using .env files to write configuration as environmental variables.

References