Making application configuration standardized. Have you ever dug into a program that someone else developed and not been able to figure out where a setting is? Maybe it's in a file somewhere alongside the installation? maybe it's hardcoded? If it is in a file is it .json? .yaml file maybe?
In most cases you don't know until you already have been given the answer. The configparser library built into python seeks to solve at least the problem of various formats by creating a native python standard configuration syntax all wrapped up into a simple to use module.
Config files are files used to store and check the configuration of a program. Specifically the config files we will be talking about in this post are ones most syntactically similar to .ini files.
As I mentioned in the description the configparser module is a python standard library module that standardizes program configurations. It does this by creating files that are syntactically similar to .ini files. One key difference to most other forms of configuration files is that type casting has to be done on deserialization. configparser stores and retrieves everything as strings so any casting needs to be done in application logic.
The demo code at the end can be run by adding it to a file and running python configparser_demo.py
or python3 configparser_demo.py
.
Any application that has state that needs to be stored and accessed can make good use of the configparser module. Also since this is a standard built into python you know that anyone using python has easy access to serialization and deserialization of the files.
from os import path # Used to check if file already exists
from configparser import ConfigParser # Used to serialize and deserialize config files
config = ConfigParser() # Create ConfigParser instance
if path.exists("demo.ini"): # If the file already exists
config.read("demo.ini") # Read it
for value in config["Application"]: # Iterate through 'application' section
print(f"{value}: {config['Application'][value]}") # Read config settings
else: # if no file exists
config["Application"] = {
"Name": "Demo application",
"Version": 1,
"Public": True
} # initialize a config
with open("demo.ini", "w") as config_file:
config.write(config_file) # Write the config object to 'demo.ini'