Hierarchical Configuration

1.0.4 · active · verified Thu Apr 16

Hierarchical-conf is a Python library designed for loading settings from YAML files in a hierarchical manner. It processes a list of paths, loading configuration files and overwriting duplicated keys based on file precedence. The library supports Python 3.7+ and is currently at version 1.0.4, with releases appearing to be made as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `hierarchical-conf` to load configurations based on the `ENVIRONMENT` variable. It creates two sample YAML files for 'dev' and 'production' environments, then loads and prints configuration values, showing how the `ENVIRONMENT` variable influences which settings are applied.

import os
from pathlib import Path
from hierarchical_conf.hierarchical_conf import HierarchicalConf

# Create dummy config files
project_root = Path(os.getcwd()) / 'my_configs'
project_root.mkdir(exist_ok=True)

(project_root / 'dev_conf.yml').write_text('database: { host: dev_db, port: 5432 }\nlog_level: DEBUG')
(project_root / 'production_conf.yml').write_text('database: { host: prod_db, port: 5432 }\nlog_level: INFO')

# Set environment variable (simulate 'dev' environment)
os.environ['ENVIRONMENT'] = 'dev'

# Initialize HierarchicalConf
hconf = HierarchicalConf(conf_files_paths=[str(project_root)])

# Get configuration for 'database'
db_config = hconf.get_config('database')
print(f"Database config (dev): {db_config}")

# Get configuration for 'log_level'
log_level = hconf.get_config('log_level')
print(f"Log level (dev): {log_level}")

# Switch environment to production
os.environ['ENVIRONMENT'] = 'production'

# Re-initialize to pick up new environment (or load another instance)
hconf_prod = HierarchicalConf(conf_files_paths=[str(project_root)])
prod_db_config = hconf_prod.get_config('database')
print(f"Database config (production): {prod_db_config}")

prod_log_level = hconf_prod.get_config('log_level')
print(f"Log level (production): {prod_log_level}")

# Clean up dummy files
# os.remove(project_root / 'dev_conf.yml')
# os.remove(project_root / 'production_conf.yml')
# os.rmdir(project_root)

view raw JSON →