PyHOCON
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
- gotcha The `pyparsing` dependency version constraint was updated from `~=2.0` to `>=2,<4` in version `0.3.60`. If your project has a specific older `pyparsing` version pinned or relies on `pyparsing` 3.x series, this change might cause dependency conflicts or unexpected behavior.
- gotcha Substitution resolution logic, especially for complex or nested substitutions, has received multiple fixes and enhancements across minor versions (e.g., 0.3.54, 0.3.58, 0.3.61). Behavior involving environment variables, cross-config resolutions, and override order might differ subtly between versions.
- gotcha In version `0.3.57`, the logic for resolving package-relative paths was rewritten, and the internal `asset` library was removed. This change might subtly alter how `pyhocon` resolves relative file paths within HOCON `include` directives, especially if you had configurations that relied on specific interpretations of relative paths prior to this version.
Install
-
pip install pyhocon
Imports
- ConfigFactory
from pyhocon import ConfigFactory
- HOCONConverter
from pyhocon import HOCONConverter
- ConfigTree
from pyhocon import ConfigTree
Quickstart
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")