Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Ytosko/7cd53469b500917e716ed9e923b5caf6 to your computer and use it in GitHub Desktop.

Select an option

Save Ytosko/7cd53469b500917e716ed9e923b5caf6 to your computer and use it in GitHub Desktop.
Managing Application Configurations with TOML in Python

Configuration and Script Example

Here are the two requested items:

1. config.toml

Create a file named config.toml with the following content:

[database]
host = "localhost"

[api_settings]
timeout_seconds = 30

2. read_config.py Script

Create a file named read_config.py with the following Python code. This script dynamically imports tomllib (for Python 3.11+) or tomli (for older Python versions), reads config.toml, and prints the specified values.

import sys

# Dynamically import tomllib (Python 3.11+) or tomli
try:
    if sys.version_info >= (3, 11):
        import tomllib
    else:
        import tomli
    _toml_parser = tomllib if sys.version_info >= (3, 11) else tomli
except ImportError:
    module_name = "tomllib" if sys.version_info >= (3, 11) else "tomli"
    print(f"Error: Required module '{module_name}' not found.")
    print(f"For Python versions < 3.11, install 'tomli': pip install tomli")
    sys.exit(1)

CONFIG_FILE_PATH = "config.toml"

def read_and_print_config():
    """
    Reads the config.toml file and prints database host and API timeout.
    """
    try:
        with open(CONFIG_FILE_PATH, "rb") as f:
            config_data = _toml_parser.load(f)

        database_host = config_data.get("database", {}).get("host")
        api_timeout_seconds = config_data.get("api_settings", {}).get("timeout_seconds")

        print(f"Database Host: {database_host}")
        print(f"API Timeout (seconds): {api_timeout_seconds}")

    except FileNotFoundError:
        print(f"Error: The file '{CONFIG_FILE_PATH}' was not found. Please ensure it exists.")
    except Exception as e:
        print(f"An error occurred while reading the config file: {e}")

if __name__ == "__main__":
    read_and_print_config()

Running the Script

To execute the read_config.py script, use the following command in your terminal:

python read_config.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment