Separating configuration information (such as database connection details, debug mode flags, and timeout settings) into external files is a fundamental practice in software development. Python provides a standard library called configparser to handle INI files, a simple format that has been used for a long time.
This article explains the structure of INI files and how to properly read strings, numbers, and boolean values using configparser.
1. Preparing the INI File
First, prepare the configuration file config.ini to be read. An INI file consists of [Section Names] and key = value pairs.
config.ini
Ini, TOML
[SERVER]
host = 192.168.1.10
port = 8080
debug_mode = yes
[APP_SETTINGS]
timeout = 15.5
max_users = 100
admin_email = admin@example.com
2. Loading the File
In your Python script, import the configparser module, create a parser object, and read the file.
import configparser
# Create parser
config = configparser.ConfigParser()
# Read configuration file (encoding specification is recommended)
config.read("config.ini", encoding="utf-8")
# Check if it loaded by printing section names
print(f"Sections: {config.sections()}")
Output:
Sections: ['SERVER', 'APP_SETTINGS']
3. How to Retrieve Values
configparser reads all configuration values as strings. However, you often want to treat ports as integers, timeouts as floats, and debug modes as booleans. Dedicated methods (getint, getfloat, getboolean) are provided to perform these type conversions automatically.
Getting as String (get or [])
Use the basic get() method or access it like a dictionary using [].
# Get 'host' key from [SERVER] section
host_val = config.get("SERVER", "host")
# Access using [] is also possible (often more intuitive)
admin_mail = config["APP_SETTINGS"]["admin_email"]
print(f"Host: {host_val} (Type: {type(host_val)})")
print(f"Email: {admin_mail}")
Output:
Host: 192.168.1.10 (Type: <class 'str'>)
Email: admin@example.com
Getting as Integer (getint)
Use this when you need an integer, such as for port numbers or counts.
# Get 'port' (8080) from [SERVER] as integer
port_val = config.getint("SERVER", "port")
# Get 'max_users' (100) from [APP_SETTINGS] as integer
max_users = config.getint("APP_SETTINGS", "max_users")
print(f"Port: {port_val} (Type: {type(port_val)})")
Output:
Port: 8080 (Type: <class 'int'>)
Getting as Float (getfloat)
Use this when you need a decimal number, such as for timeout durations or rates.
# Get 'timeout' (15.5) from [APP_SETTINGS] as float
timeout_val = config.getfloat("APP_SETTINGS", "timeout")
print(f"Timeout: {timeout_val} (Type: {type(timeout_val)})")
Output:
Timeout: 15.5 (Type: <class 'float'>)
Getting as Boolean (getboolean)
This is a very convenient feature of configparser. If the INI file contains yes/no, on/off, true/false, or 1/0, it correctly converts them into Python True / False boolean values.
# Get 'debug_mode' (yes) from [SERVER] as boolean
is_debug = config.getboolean("SERVER", "debug_mode")
print(f"Debug Mode: {is_debug} (Type: {type(is_debug)})")
if is_debug:
print("Running in Debug Mode.")
Output:
Debug Mode: True (Type: <class 'bool'>)
Running in Debug Mode.
Summary
Using configparser makes it easy to handle INI files.
config.read("filename"): Loads the file.config["Section"]["Key"]: Gets value as a string (Basic usage).config.getint(): Gets value as an integer.config.getfloat(): Gets value as a float.config.getboolean(): Gets value asTruefor inputs likeyes,on,1.
By using methods appropriate for the data type, you can save the trouble of manual type conversion in your code and prevent errors.
