PyHOCON

0.3.63 · active · verified Thu Apr 09

PyHOCON is a Python parser for the HOCON (Human Optimized Config Object Notation) configuration format. It allows for reading, parsing, and manipulating HOCON configuration files and strings, including support for substitutions, includes, and various data types. The library is actively maintained with irregular but consistent minor releases, currently at version 0.3.63.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse HOCON configuration from both a string and a file using `ConfigFactory`. It also shows how to use environment variable substitutions and how to convert a parsed configuration back into a HOCON string using `HOCONConverter`.

import os
from pyhocon import ConfigFactory, HOCONConverter

# Example HOCON string
hocon_string = """
app {
    name = "MyApplication"
    version = "1.0.0"
    features = [
        { id = 1, enabled = true },
        { id = 2, enabled = false }
    ]
    environment = ${?ENV_NAME} # Optional environment variable substitution
}
"""

# Parse from a string
config_from_string = ConfigFactory.parse_string(hocon_string)
print(f"Config from string: {config_from_string.get('app.name')}")

# Set an environment variable for substitution demonstration
os.environ['ENV_NAME'] = 'production'
config_from_string = ConfigFactory.parse_string(hocon_string)
print(f"Config environment: {config_from_string.get('app.environment')}")
os.environ.pop('ENV_NAME') # Clean up

# Create a dummy config file for parsing
file_content = """
database {
    host = "localhost"
    port = 5432
    user = "admin"
}
"""
with open("config.conf", "w") as f:
    f.write(file_content)

# Parse from a file
config_from_file = ConfigFactory.parse_file("config.conf")
print(f"Config from file: {config_from_file.get('database.host')}")

# Convert a ConfigTree back to HOCON string
hocon_output = HOCONConverter.to_hocon(config_from_string)
print("\nConverted HOCON output:\n", hocon_output)

# Clean up dummy file
os.remove("config.conf")

view raw JSON →