### HOCON file example Source: https://github.com/chimpler/pyhocon/blob/master/README.md An example of a HOCON configuration file demonstrating various features including comments, nested objects, substitutions with environment variables, lists with different separators, and list/dictionary merging. ```hocon // // You can use # or // for comments // { databases { # MySQL active = true enable_logging = false resolver = null # you can use substitution with unquoted strings. If it it not found in the document, it defaults to environment variables home_dir = ${HOME} # you can substitute with environment variables "mysql" = { host = "abc.com" # change it port = 3306 # default username: scott // can use : or = password = tiger, // can optionally use a comma // number of retries retries = 3 } } // multi line support motd = """ Hello "man"! How is it going? """ // this will be appended to the databases dictionary above databases.ips = [ 192.168.0.1 // use white space or comma as separator "192.168.0.2" // optional quotes 192.168.0.3, # can have a trailing , which is ok ] # you can use substitution with unquoted strings retries_msg = You have ${databases.mysql.retries} retries # retries message will be overridden if environment variable CUSTOM_MSG is set retries_msg = ${?CUSTOM_MSG} } // dict merge data-center-generic = { cluster-size = 6 } data-center-east = ${data-center-generic} { name = "east" } // list merge default-jvm-opts = [-XX:+UseParNewGC] large-jvm-opts = ${default-jvm-opts} [-Xm16g] ``` -------------------------------- ### Parse HOCON file and get string value Source: https://github.com/chimpler/pyhocon/blob/master/README.md Demonstrates parsing a HOCON file and retrieving a string value using different access methods. Includes examples of direct dictionary access, path-based access, and using the `get_string` method. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_file('samples/database.conf') host = conf.get_string('databases.mysql.host') same_host = conf.get('databases.mysql.host') same_host = conf['databases.mysql.host'] same_host = conf['databases']['mysql.host'] port = conf['databases.mysql.port'] username = conf['databases']['mysql']['username'] password = conf.get_config('databases')['mysql.password'] password = conf.get('databases.mysql.password', 'default_password') # use default value if key not found ``` -------------------------------- ### Convert HOCON files via command-line friendly method Source: https://context7.com/chimpler/pyhocon/llms.txt Use convert_from_file to transform configuration files between formats like JSON, YAML, and properties. ```python from pyhocon import HOCONConverter # Convert file to JSON HOCONConverter.convert_from_file( input_file='config.conf', output_file='config.json', output_format='json', indent=2 ) # Convert to YAML with compact mode HOCONConverter.convert_from_file( input_file='config.conf', output_file='config.yaml', output_format='yaml', compact=True ) # Convert to properties HOCONConverter.convert_from_file( input_file='config.conf', output_file='config.properties', output_format='properties' ) ``` -------------------------------- ### Retrieve values with ConfigTree.get Source: https://context7.com/chimpler/pyhocon/llms.txt Accesses configuration values using dot-separated paths with support for default values. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { database { mysql { host = "db.example.com" port = 3306 enabled = true } } } """) # Get with default value host = conf.get('database.mysql.host') timeout = conf.get('database.mysql.timeout', 30) # Returns 30 if not found # Alternative access methods host = conf['database.mysql.host'] host = conf['database']['mysql']['host'] host = conf['database']['mysql.host'] ``` -------------------------------- ### Parse HOCON from file Source: https://context7.com/chimpler/pyhocon/llms.txt Loads configuration from a filesystem path. Supports custom encoding and optional file loading. ```python from pyhocon import ConfigFactory # Parse a HOCON configuration file conf = ConfigFactory.parse_file('database.conf') # Access values using dot notation paths host = conf['databases.mysql.host'] port = conf['databases.mysql.port'] # Access nested dictionaries mysql_config = conf['databases']['mysql'] username = mysql_config['username'] # With custom encoding and optional file loading conf = ConfigFactory.parse_file( 'config.conf', encoding='utf-8', required=False, # Returns [] if file not found resolve=True # Resolve substitutions (default) ) ``` -------------------------------- ### Create ConfigTree from dictionary Source: https://context7.com/chimpler/pyhocon/llms.txt Converts a Python dictionary into a ConfigTree. Use OrderedDict to preserve key order. ```python from collections import OrderedDict from pyhocon import ConfigFactory # Create config from regular dictionary config_dict = { 'server': { 'host': 'localhost', 'port': 8080 }, 'features': ['auth', 'logging', 'caching'] } conf = ConfigFactory.from_dict(config_dict) # Create config from OrderedDict to preserve key order ordered = OrderedDict([ ('first', 1), ('second', 2), ('third', 3) ]) conf = ConfigFactory.from_dict(ordered) # Access values print(conf['server.host']) # Output: localhost print(conf['features']) # Output: ['auth', 'logging', 'caching'] ``` -------------------------------- ### Convert ConfigTree to Java properties Source: https://context7.com/chimpler/pyhocon/llms.txt Export a configuration object to the Java .properties file format. ```python from pyhocon import ConfigFactory from pyhocon import HOCONConverter conf = ConfigFactory.parse_string(""" { app { name = "MyApplication" version = "1.0.0" } database { host = "localhost" port = 3306 } features = ["auth", "cache"] } """) props_output = HOCONConverter.to_properties(conf) print(props_output) # Output: # app.name = MyApplication # app.version = 1.0.0 # database.host = localhost # database.port = 3306 # features.0 = auth # features.1 = cache ``` -------------------------------- ### ConfigFactory.from_dict Source: https://context7.com/chimpler/pyhocon/llms.txt Creates a ConfigTree object from a Python dictionary, preserving order if OrderedDict is used. ```APIDOC ## ConfigFactory.from_dict ### Description Create a ConfigTree from a Python dictionary. Preserves order when using OrderedDict. ### Method `ConfigFactory.from_dict(d)` ### Endpoint N/A (Dictionary Operation) ### Parameters #### Path Parameters - **d** (dict or OrderedDict) - Required - The Python dictionary or OrderedDict to convert. ### Request Example ```python from collections import OrderedDict from pyhocon import ConfigFactory # Create config from regular dictionary config_dict = { 'server': { 'host': 'localhost', 'port': 8080 }, 'features': ['auth', 'logging', 'caching'] } conf = ConfigFactory.from_dict(config_dict) # Create config from OrderedDict to preserve key order ordered = OrderedDict([ ('first', 1), ('second', 2), ('third', 3) ]) conf = ConfigFactory.from_dict(ordered) # Access values print(conf['server.host']) # Output: localhost print(conf['features']) # Output: ['auth', 'logging', 'caching'] ``` ### Response #### Success Response (200) - **ConfigTree** - An object providing dictionary-like access to configuration values. #### Response Example ```json { "server": { "host": "localhost", "port": 8080 }, "features": [ "auth", "logging", "caching" ] } ``` ``` -------------------------------- ### Merge configurations with with_fallback Source: https://context7.com/chimpler/pyhocon/llms.txt Combines two configurations where the primary configuration takes precedence over the fallback configuration. ```python from pyhocon import ConfigFactory # Base/default configuration default_conf = ConfigFactory.parse_string(""" { server { host = "localhost" port = 8080 timeout = 30 } logging { level = "INFO" } } """) # Override configuration override_conf = ConfigFactory.parse_string(""" { server { host = "production.example.com" port = 443 } } """) ``` -------------------------------- ### Merge configurations with fallback Source: https://context7.com/chimpler/pyhocon/llms.txt Use with_fallback to provide default values that are overridden by the primary configuration. ```python # Merge with fallback: override_conf takes precedence, defaults fill gaps final_conf = override_conf.with_fallback(default_conf) print(final_conf['server.host']) # Output: production.example.com (from override) print(final_conf['server.port']) # Output: 443 (from override) print(final_conf['server.timeout']) # Output: 30 (from default fallback) print(final_conf['logging.level']) # Output: INFO (from default fallback) # Can also pass a filename directly conf = override_conf.with_fallback('defaults.conf') ``` -------------------------------- ### ConfigTree.get Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a value from the configuration tree using dot-separated path notation, with an option for a default value. ```APIDOC ## ConfigTree.get ### Description Retrieve a value from the configuration tree using dot-separated path notation. Returns a default value if the key is not found. ### Method `ConfigTree.get(path, default=None)` ### Endpoint N/A (Object Method) ### Parameters #### Path Parameters - **path** (string) - Required - The dot-separated path to the desired configuration value. - **default** (any) - Optional - The value to return if the path is not found (default: None). ### Request Example ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { database { mysql { host = "db.example.com" port = 3306 enabled = true } } } """) # Get with default value host = conf.get('database.mysql.host') timeout = conf.get('database.mysql.timeout', 30) # Returns 30 if not found # Alternative access methods host_alt1 = conf['database.mysql.host'] host_alt2 = conf['database']['mysql']['host'] host_alt3 = conf['database']['mysql.host'] ``` ### Response #### Success Response (200) - **value** (any) - The configuration value found at the specified path, or the default value if not found. #### Response Example ```json "db.example.com" ``` #### Response Example (with default) ```json 30 ``` ``` -------------------------------- ### Python: Create Config from Dictionary Source: https://github.com/chimpler/pyhocon/blob/master/README.md Use `ConfigFactory.from_dict()` to create a Pyhocon configuration object directly from a Python dictionary. This is useful for dynamic configuration generation. ```python from collections import OrderedDict d = OrderedDict() d['banana'] = 3 d['apple'] = 4 d['pear'] = 1 d['orange'] = 2 config = ConfigFactory.from_dict(d) assert config == d ``` -------------------------------- ### Include Configuration Files Source: https://github.com/chimpler/pyhocon/blob/master/README.md Pyhocon supports including other configuration files using various syntaxes, including relative paths, URLs, and package resources. Relative paths are resolved based on the including file's directory or the current directory if using standard input. ```hocon include "test.conf" include "http://abc.com/test.conf" include "https://abc.com/test.conf" include "file://abc.com/test.conf" include file("test.conf") include required(file("test.conf")) include url("http://abc.com/test.conf") include url("https://abc.com/test.conf") include url("file://abc.com/test.conf") include package("package:assets/test.conf") ``` -------------------------------- ### ConfigTree.get_list Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a configuration value as a list. Can also convert numerically-indexed dictionaries to lists. ```APIDOC ## ConfigTree.get_list ### Description Retrieve a value as a list. Can also convert numerically-indexed dictionaries to lists. ### Method `get_list(path, default=None)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the configuration value. - **default** (list) - Optional - The default value to return if the path is not found. ### Request Example ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { servers = [ "server1.example.com" "server2.example.com" "server3.example.com" ] ports = [8080, 8081, 8082] # Numerically indexed dictionary (converted to list) indexed { 0 = "first" 1 = "second" 2 = "third" } } """) servers = conf.get_list('servers') ports = conf.get_list('ports') indexed = conf.get_list('indexed') ``` ### Response #### Success Response (list) - Returns the configuration value as a list. #### Response Example ``` ['server1.example.com', 'server2.example.com', 'server3.example.com'] [8080, 8081, 8082] ['first', 'second', 'third'] ``` ``` -------------------------------- ### Configuration Merging with Includes Source: https://github.com/chimpler/pyhocon/blob/master/README.md Demonstrates how Pyhocon merges configurations when using includes. Attributes from included files are merged into the parent configuration, with later definitions overwriting earlier ones. ```hocon cat.conf: { garfield: { say: meow } } dog.conf: { mutt: { say: woof hates: { garfield: { notes: I don't like him say: meeeeeeeooooowww } include "cat.conf" } } } animals.conf: { cat : { include "cat.conf" } dog: { include "dog.conf" } } ``` ```json $ pyhocon -i samples/animals.conf { "cat": { "garfield": { "say": "meow" } }, "dog": { "mutt": { "say": "woof", "hates": { "garfield": { "notes": "I don't like him", "say": "meow" } } } } } ``` -------------------------------- ### ConfigTree.get_string Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a configuration value as a string. Booleans are converted to lowercase strings ('true'/'false'). ```APIDOC ## ConfigTree.get_string ### Description Retrieve a value as a string representation. Converts booleans to lowercase strings ("true"/"false"). ### Method `get_string(path, default=None)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the configuration value. - **default** (any) - Optional - The default value to return if the path is not found. ### Request Example ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { settings { name = "MyApp" version = 1.5 enabled = true count = 42 } } """) name = conf.get_string('settings.name') version = conf.get_string('settings.version') enabled = conf.get_string('settings.enabled') count = conf.get_string('settings.count') missing = conf.get_string('settings.missing', 'default') ``` ### Response #### Success Response (string) - Returns the configuration value as a string. #### Response Example ``` "MyApp" "1.5" "true" "42" "default" ``` ``` -------------------------------- ### Retrieve nested configuration with get_config Source: https://context7.com/chimpler/pyhocon/llms.txt Returns a ConfigTree object representing a nested section of the configuration. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { databases { mysql { host = "mysql.example.com" port = 3306 } postgres { host = "postgres.example.com" port = 5432 } } } """) # Get nested config section mysql_conf = conf.get_config('databases.mysql') print(mysql_conf['host']) # Output: mysql.example.com print(mysql_conf['port']) # Output: 3306 # Get parent config and access children db_conf = conf.get_config('databases') pg_host = db_conf['postgres.host'] # Output: postgres.example.com ``` -------------------------------- ### Include external HOCON files Source: https://context7.com/chimpler/pyhocon/llms.txt Use the include directive to merge local files, URLs, or package resources into the main configuration. ```python from pyhocon import ConfigFactory # Main config file (app.conf): # { # include "database.conf" # include "http://config-server/common.conf" # include file("local-overrides.conf") # include required(file("required-settings.conf")) # include url("https://config.example.com/app.conf") # include package("mypackage:config/defaults.conf") # # app { # name = "MyApp" # } # } # Parse with includes resolved conf = ConfigFactory.parse_file('app.conf') # Wildcard includes # include "conf.d/*.conf" ``` -------------------------------- ### Convert ConfigTree to YAML Source: https://context7.com/chimpler/pyhocon/llms.txt Export a configuration object to a YAML string format. ```python from pyhocon import ConfigFactory from pyhocon import HOCONConverter conf = ConfigFactory.parse_string(""" { database { host = "db.example.com" port = 5432 credentials { user = "admin" pass = "secret" } } replicas = [1, 2, 3] } """) yaml_output = HOCONConverter.to_yaml(conf) print(yaml_output) # Output: # database: # host: db.example.com # port: 5432 # credentials: # user: admin # pass: secret # replicas: # - 1 # - 2 # - 3 ``` -------------------------------- ### Retrieve integer values with get_int Source: https://context7.com/chimpler/pyhocon/llms.txt Extracts values as integers, raising a ConfigException if conversion fails. Supports an optional default value. ```python from pyhocon import ConfigFactory from pyhocon.exceptions import ConfigException conf = ConfigFactory.parse_string(""" { server { port = 8080 max_connections = 100 timeout = 30 } } """) port = conf.get_int('server.port') # Output: 8080 max_conn = conf.get_int('server.max_connections') # Output: 100 missing = conf.get_int('server.missing', 0) # Output: 0 (default) try: invalid = conf.get_int('server.name') except ConfigException as e: print(f"Error: {e}") ``` -------------------------------- ### Convert ConfigTree to HOCON Source: https://context7.com/chimpler/pyhocon/llms.txt Export a configuration object back to HOCON format, with an optional compact mode for nested single-element dictionaries. ```python from pyhocon import ConfigFactory from pyhocon import HOCONConverter conf = ConfigFactory.parse_string(""" { app.server.host = "localhost" app.server.port = 8080 features = ["auth", "logging"] } """) # Standard HOCON output hocon_output = HOCONConverter.to_hocon(conf) print(hocon_output) # Compact mode (collapses nested single-element dicts) hocon_compact = HOCONConverter.to_hocon(conf, compact=True) print(hocon_compact) # Output: app.server.host = "localhost" # app.server.port = 8080 # features = ["auth", "logging"] ``` -------------------------------- ### Convert ConfigTree to JSON Source: https://context7.com/chimpler/pyhocon/llms.txt Export a configuration object to a JSON string, with optional indentation support. ```python from pyhocon import ConfigFactory from pyhocon import HOCONConverter conf = ConfigFactory.parse_string(""" { server { host = "localhost" port = 8080 ssl = true } tags = ["web", "api", "v2"] } """) # Convert to JSON json_output = HOCONConverter.to_json(conf) print(json_output) # Output: # { # "server": { # "host": "localhost", # "port": 8080, # "ssl": true # }, # "tags": [ # "web", # "api", # "v2" # ] # } # With custom indentation json_compact = HOCONConverter.to_json(conf, indent=4) ``` -------------------------------- ### pyhocon conversion tool usage Source: https://github.com/chimpler/pyhocon/blob/master/README.md Command-line usage for the pyhocon conversion tool, which converts HOCON files to JSON, .properties, and YAML formats. It details the available arguments for input, output, format, and indentation. ```bash usage: tool.py [-h] [-i INPUT] [-o OUTPUT] [-f FORMAT] [-n INDENT] [-v] pyhocon tool optional arguments: -h, --help show this help message and exit -i INPUT, --input INPUT input file -o OUTPUT, --output OUTPUT output file -c, --compact compact format -f FORMAT, --format FORMAT output format: json, properties, yaml or hocon -n INDENT, --indent INDENT indentation step (default is 2) -v, --verbosity increase output verbosity ``` -------------------------------- ### ConfigTree.with_fallback Source: https://context7.com/chimpler/pyhocon/llms.txt Merges two configurations, where the current configuration takes precedence. Missing values in the current config fall back to the provided config. ```APIDOC ## ConfigTree.with_fallback ### Description Merge two configurations with fallback support. The current config takes precedence; missing values fall back to the provided config. ### Method `with_fallback(other_config)` ### Parameters #### Path Parameters - **other_config** (ConfigTree) - Required - The configuration to merge with fallback support. ### Request Example ```python from pyhocon import ConfigFactory # Base/default configuration default_conf = ConfigFactory.parse_string(""" { server { host = "localhost" port = 8080 timeout = 30 } logging { level = "INFO" } } """) # Override configuration override_conf = ConfigFactory.parse_string(""" { server { host = "production.example.com" port = 443 } } """) # Merge with fallback merged_conf = override_conf.with_fallback(default_conf) print(merged_conf.get_string('server.host')) # Output: production.example.com print(merged_conf.get_int('server.port')) # Output: 443 print(merged_conf.get_int('server.timeout')) # Output: 30 (from default_conf) print(merged_conf.get_string('logging.level')) # Output: INFO (from default_conf) ``` ### Response #### Success Response (ConfigTree) - Returns a new `ConfigTree` object with the merged configurations. #### Response Example ``` production.example.com 443 30 INFO ``` ``` -------------------------------- ### ConfigFactory.parse_file Source: https://context7.com/chimpler/pyhocon/llms.txt Parses a HOCON configuration file from the filesystem. It returns a ConfigTree object for accessing configuration values. ```APIDOC ## ConfigFactory.parse_file ### Description Parse a HOCON configuration file from the filesystem. Returns a `ConfigTree` object that provides dictionary-like access to configuration values with automatic type inference. ### Method `ConfigFactory.parse_file(path, encoding='utf-8', required=True, resolve=True)` ### Endpoint N/A (File System Operation) ### Parameters #### Path Parameters - **path** (string) - Required - The path to the HOCON configuration file. #### Query Parameters - **encoding** (string) - Optional - The encoding of the file (default: 'utf-8'). - **required** (boolean) - Optional - If True, raises an exception if the file is not found. If False, returns an empty list (default: True). - **resolve** (boolean) - Optional - Whether to resolve substitutions (default: True). ### Request Example ```python from pyhocon import ConfigFactory # Parse a HOCON configuration file conf = ConfigFactory.parse_file('database.conf') # Access values using dot notation paths host = conf['databases.mysql.host'] port = conf['databases.mysql.port'] # Access nested dictionaries mysql_config = conf['databases']['mysql'] username = mysql_config['username'] # With custom encoding and optional file loading conf = ConfigFactory.parse_file( 'config.conf', encoding='utf-8', required=False, # Returns [] if file not found resolve=True # Resolve substitutions (default) ) ``` ### Response #### Success Response (200) - **ConfigTree** - An object providing dictionary-like access to configuration values. #### Response Example ```json { "databases": { "mysql": { "host": "localhost", "port": 3306, "username": "admin" } } } ``` ``` -------------------------------- ### ConfigTree.get_bool Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a configuration value as a boolean. Supports string conversions like 'true'/'yes'/'on' for True and 'false'/'no'/'off' for False. ```APIDOC ## ConfigTree.get_bool ### Description Retrieve a value as a boolean. Supports string conversions: "true"/"yes"/"on" = True, "false"/"no"/"off" = False. ### Method `get_bool(path, default=None)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the configuration value. - **default** (bool) - Optional - The default value to return if the path is not found. ### Request Example ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { features { enabled = true debug = yes ssl = on logging = false cache = no compress = off } } """) enabled = conf.get_bool('features.enabled') debug = conf.get_bool('features.debug') ssl = conf.get_bool('features.ssl') logging = conf.get_bool('features.logging') cache = conf.get_bool('features.cache') compress = conf.get_bool('features.compress') ``` ### Response #### Success Response (bool) - Returns the configuration value as a boolean. #### Response Example ``` True True True False False False ``` ``` -------------------------------- ### ConfigTree.get_int Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a configuration value as an integer. Raises ConfigException if the value cannot be converted to an integer. ```APIDOC ## ConfigTree.get_int ### Description Retrieve a value as an integer. Raises ConfigException if the value cannot be converted to int. ### Method `get_int(path, default=None)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the configuration value. - **default** (int) - Optional - The default value to return if the path is not found. ### Request Example ```python from pyhocon import ConfigFactory from pyhocon.exceptions import ConfigException conf = ConfigFactory.parse_string(""" { server { port = 8080 max_connections = 100 timeout = 30 } } """) port = conf.get_int('server.port') max_conn = conf.get_int('server.max_connections') missing = conf.get_int('server.missing', 0) try: invalid = conf.get_int('server.name') except ConfigException as e: print(f"Error: {e}") ``` ### Response #### Success Response (int) - Returns the configuration value as an integer. #### Error Response (ConfigException) - Raises `ConfigException` if the value cannot be converted to an integer. #### Response Example ``` 8080 100 0 Error: Cannot convert 'server.name' to int ``` ``` -------------------------------- ### Parse HOCON from URL Source: https://context7.com/chimpler/pyhocon/llms.txt Loads configuration from a remote URL with support for HTTP, HTTPS, and file protocols. ```python from pyhocon import ConfigFactory # Parse configuration from a URL conf = ConfigFactory.parse_URL( 'https://example.com/config/app.conf', timeout=30, # Timeout in seconds required=False, # Returns [] if URL is inaccessible resolve=True # Resolve substitutions ) # Access configuration values api_endpoint = conf.get('api.endpoint', 'http://localhost:8080') ``` -------------------------------- ### Handle configuration exceptions Source: https://context7.com/chimpler/pyhocon/llms.txt Catch specific pyhocon exceptions to manage missing keys, type mismatches, or substitution errors gracefully. ```python from pyhocon import ConfigFactory from pyhocon.exceptions import ( ConfigException, ConfigMissingException, ConfigWrongTypeException, ConfigSubstitutionException ) try: conf = ConfigFactory.parse_file('config.conf') # ConfigMissingException for missing keys value = conf['nonexistent.key'] except ConfigMissingException as e: print(f"Key not found: {e}") except ConfigWrongTypeException as e: print(f"Type mismatch: {e}") except ConfigSubstitutionException as e: print(f"Substitution error: {e}") except ConfigException as e: print(f"Configuration error: {e}") # Safe access with defaults value = conf.get('optional.key', 'default_value') ``` -------------------------------- ### ConfigTree.get_float Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a configuration value as a floating-point number. Raises ConfigException if the value cannot be converted to a float. ```APIDOC ## ConfigTree.get_float ### Description Retrieve a value as a floating-point number. Raises ConfigException if the value cannot be converted to float. ### Method `get_float(path, default=None)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the configuration value. - **default** (float) - Optional - The default value to return if the path is not found. ### Request Example ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { metrics { threshold = 0.95 rate = 1.5 precision = 3.14159 } } """) threshold = conf.get_float('metrics.threshold') rate = conf.get_float('metrics.rate') default = conf.get_float('metrics.missing', 0.0) ``` ### Response #### Success Response (float) - Returns the configuration value as a float. #### Response Example ``` 0.95 1.5 0.0 ``` ``` -------------------------------- ### HOCONConverter Methods Source: https://context7.com/chimpler/pyhocon/llms.txt Methods for converting ConfigTree objects into different serialization formats including JSON, YAML, properties, and HOCON. ```APIDOC ## HOCONConverter.to_json ### Description Convert a ConfigTree to JSON string format. ## HOCONConverter.to_yaml ### Description Convert a ConfigTree to YAML string format. ## HOCONConverter.to_properties ### Description Convert a ConfigTree to Java .properties format. ## HOCONConverter.to_hocon ### Description Convert a ConfigTree back to HOCON format. Supports compact mode for nested single-element dictionaries. ## HOCONConverter.convert_from_file ### Description Command-line friendly method to convert HOCON files to other formats. Reads from stdin if no input file specified, writes to stdout if no output file specified. ``` -------------------------------- ### Statically merge ConfigTree objects Source: https://context7.com/chimpler/pyhocon/llms.txt Merge two ConfigTree objects where the source configuration values take precedence over the target. ```python from pyhocon import ConfigFactory from pyhocon.config_tree import ConfigTree config_a = ConfigFactory.parse_string(""" { app { name = "MyApp" version = "1.0" } database { host = "localhost" } } """) config_b = ConfigFactory.parse_string(""" { app { version = "2.0" author = "Developer" } database { port = 5432 } } """) # Merge config_b into config_a (modifies config_a in place) merged = ConfigTree.merge_configs(config_a, config_b) print(merged['app.name']) # Output: MyApp (from config_a) print(merged['app.version']) # Output: 2.0 (overwritten by config_b) print(merged['app.author']) # Output: Developer (added from config_b) print(merged['database.host']) # Output: localhost (from config_a) print(merged['database.port']) # Output: 5432 (added from config_b) ``` -------------------------------- ### Convert HOCON formats via CLI Source: https://context7.com/chimpler/pyhocon/llms.txt Use the pyhocon command-line tool to convert between HOCON, JSON, YAML, and properties formats, or to validate and debug configurations. ```bash # Convert HOCON to JSON (default) pyhocon -i config.conf -o config.json # Convert HOCON to YAML pyhocon -i config.conf -o config.yaml -f yaml # Convert HOCON to .properties pyhocon -i config.conf -o config.properties -f properties # Read from stdin, write to stdout cat config.conf | pyhocon -f json # Compact output format pyhocon -i config.conf -f hocon -c # Custom indentation (4 spaces) pyhocon -i config.conf -f json -n 4 # Verbose output for debugging pyhocon -i config.conf -f json -v pyhocon -i config.conf -f json -vv # More verbose pyhocon -i config.conf -f json -vvv # Debug level ``` -------------------------------- ### ConfigTree.get_config Source: https://context7.com/chimpler/pyhocon/llms.txt Retrieves a nested configuration subtree, returning a ConfigTree object for accessing nested sections. ```APIDOC ## ConfigTree.get_config ### Description Retrieve a nested configuration subtree. Returns a ConfigTree object for accessing nested configuration sections. ### Method `get_config(path, default=None)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the nested configuration section. - **default** (ConfigTree) - Optional - The default ConfigTree to return if the path is not found. ### Request Example ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { databases { mysql { host = "mysql.example.com" port = 3306 } postgres { host = "postgres.example.com" port = 5432 } } } """) # Get nested config section mysql_conf = conf.get_config('databases.mysql') print(mysql_conf['host']) print(mysql_conf['port']) # Get parent config and access children db_conf = conf.get_config('databases') pg_host = db_conf['postgres.host'] ``` ### Response #### Success Response (ConfigTree) - Returns a `ConfigTree` object representing the nested configuration section. #### Response Example ``` mysql.example.com 3306 postgres.example.com ``` ``` -------------------------------- ### Retrieve float values with get_float Source: https://context7.com/chimpler/pyhocon/llms.txt Extracts values as floating-point numbers, raising a ConfigException if conversion fails. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { metrics { threshold = 0.95 rate = 1.5 precision = 3.14159 } } """) threshold = conf.get_float('metrics.threshold') # Output: 0.95 rate = conf.get_float('metrics.rate') # Output: 1.5 default = conf.get_float('metrics.missing', 0.0) # Output: 0.0 ``` -------------------------------- ### Retrieve string values with get_string Source: https://context7.com/chimpler/pyhocon/llms.txt Converts values to string representation, including booleans. Supports an optional default value if the key is missing. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { settings { name = "MyApp" version = 1.5 enabled = true count = 42 } } """) name = conf.get_string('settings.name') # Output: "MyApp" version = conf.get_string('settings.version') # Output: "1.5" enabled = conf.get_string('settings.enabled') # Output: "true" count = conf.get_string('settings.count') # Output: "42" missing = conf.get_string('settings.missing', 'default') # Output: "default" ``` -------------------------------- ### ConfigTree.merge_configs Source: https://context7.com/chimpler/pyhocon/llms.txt Statically merge two ConfigTree objects where the source configuration values take precedence over the target configuration. ```APIDOC ## ConfigTree.merge_configs ### Description Statically merge two ConfigTree objects. Source config is merged into target config, with source values taking precedence. ### Parameters #### Request Body - **target** (ConfigTree) - Required - The base configuration to be modified. - **source** (ConfigTree) - Required - The configuration containing overrides. ``` -------------------------------- ### Convert HOCON to .properties Source: https://github.com/chimpler/pyhocon/blob/master/README.md Use the '-f properties' flag to convert a HOCON file to the .properties format. This is suitable for Java-based applications. ```bash $ cat samples/database.conf | pyhocon -f properties databases.active = true databases.enable_logging = false databases.home_dir = /Users/darthbear databases.mysql.host = abc.com databases.mysql.port = 3306 databases.mysql.username = scott databases.mysql.password = tiger databases.mysql.retries = 3 databases.ips.0 = 192.168.0.1 databases.ips.1 = 192.168.0.2 databases.ips.2 = 192.168.0.3 motd = \ Hello "man"!\ How is it going? retries_msg = You have 3 retries ``` -------------------------------- ### Retrieve boolean values with get_bool Source: https://context7.com/chimpler/pyhocon/llms.txt Supports common string representations for booleans such as 'yes'/'no', 'on'/'off', and 'true'/'false'. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { features { enabled = true debug = yes ssl = on logging = false cache = no compress = off } } """) enabled = conf.get_bool('features.enabled') # Output: True debug = conf.get_bool('features.debug') # Output: True ssl = conf.get_bool('features.ssl') # Output: True logging = conf.get_bool('features.logging') # Output: False cache = conf.get_bool('features.cache') # Output: False compress = conf.get_bool('features.compress') # Output: False ``` -------------------------------- ### ConfigFactory.parse_URL Source: https://context7.com/chimpler/pyhocon/llms.txt Parses HOCON configuration from a remote URL, supporting HTTP, HTTPS, and file:// protocols. ```APIDOC ## ConfigFactory.parse_URL ### Description Parse HOCON configuration from a remote URL. Supports HTTP, HTTPS, and file:// protocols with optional timeout. ### Method `ConfigFactory.parse_URL(url, timeout=None, encoding='utf-8', required=True, resolve=True)` ### Endpoint N/A (URL Operation) ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the HOCON configuration. #### Query Parameters - **timeout** (integer) - Optional - Timeout in seconds for the request. - **encoding** (string) - Optional - The encoding of the configuration content (default: 'utf-8'). - **required** (boolean) - Optional - If True, raises an exception if the URL is inaccessible. If False, returns an empty list (default: True). - **resolve** (boolean) - Optional - Whether to resolve substitutions (default: True). ### Request Example ```python from pyhocon import ConfigFactory # Parse configuration from a URL conf = ConfigFactory.parse_URL( 'https://example.com/config/app.conf', timeout=30, # Timeout in seconds required=False, # Returns [] if URL is inaccessible resolve=True # Resolve substitutions ) # Access configuration values api_endpoint = conf.get('api.endpoint', 'http://localhost:8080') ``` ### Response #### Success Response (200) - **ConfigTree** - An object providing dictionary-like access to configuration values. #### Response Example ```json { "api": { "endpoint": "http://api.example.com" } } ``` ``` -------------------------------- ### Perform variable substitution Source: https://context7.com/chimpler/pyhocon/llms.txt Use ${variable} for standard substitution or ${?variable} for optional substitution that defaults to None if the variable is missing. ```python from pyhocon import ConfigFactory import os # Set environment variable for demonstration os.environ['DB_PASSWORD'] = 'secret123' conf = ConfigFactory.parse_string(""" { base_path = "/var/app" paths { logs = ${base_path}/logs data = ${base_path}/data config = ${base_path}/config } database { host = "localhost" port = 3306 # Falls back to environment variable password = ${DB_PASSWORD} # Optional substitution (no error if missing) ssl_cert = ${?SSL_CERT_PATH} } # Self-referential substitution jvm_opts = ["-Xms512m"] jvm_opts = ${jvm_opts} ["-Xmx2g"] } """) print(conf['paths.logs']) # Output: /var/app/logs print(conf['database.password']) # Output: secret123 print(conf['database.ssl_cert']) # Output: None (optional, not set) print(conf['jvm_opts']) # Output: ['-Xms512m', '-Xmx2g'] ``` -------------------------------- ### ConfigFactory.parse_string Source: https://context7.com/chimpler/pyhocon/llms.txt Parses HOCON content directly from a string, useful for embedded configurations or testing. ```APIDOC ## ConfigFactory.parse_string ### Description Parse HOCON content directly from a string. Useful for embedded configurations or testing scenarios. ### Method `ConfigFactory.parse_string(s, resolve=True)` ### Endpoint N/A (String Operation) ### Parameters #### Path Parameters - **s** (string) - Required - The HOCON content as a string. #### Query Parameters - **resolve** (boolean) - Optional - Whether to resolve substitutions (default: True). ### Request Example ```python from pyhocon import ConfigFactory hocon_content = """ { database { host = "localhost" port = 5432 credentials { username = admin password = ${DB_PASSWORD} # Falls back to environment variable } } # List with optional trailing comma allowed_ips = [ 192.168.1.1 192.168.1.2, ] # Multi-line string welcome_message = """ Welcome to our service! Please login to continue. """ } """ conf = ConfigFactory.parse_string(hocon_content) print(conf['database.host']) # Output: localhost print(conf['database.credentials.username']) # Output: admin print(conf['allowed_ips']) # Output: ['192.168.1.1', '192.168.1.2'] ``` ### Response #### Success Response (200) - **ConfigTree** - An object providing dictionary-like access to configuration values. #### Response Example ```json { "database": { "host": "localhost", "port": 5432, "credentials": { "username": "admin", "password": null } }, "allowed_ips": [ "192.168.1.1", "192.168.1.2" ], "welcome_message": "Welcome to our service!\nPlease login to continue." } ``` ``` -------------------------------- ### Convert HOCON to YAML Source: https://github.com/chimpler/pyhocon/blob/master/README.md Use the '-f yaml' flag to convert a HOCON file to YAML format. This is useful for applications that prefer YAML configurations. ```bash $ cat samples/database.conf | pyhocon -f yaml databases: active: true enable_logging: false resolver: None home_dir: /Users/darthbear mysql: host: abc.com port: 3306 username: scott password: tiger retries: 3 ips: - 192.168.0.1 - 192.168.0.2 - 192.168.0.3 motd: | Hello "man"! How is it going? retries_msg: You have 3 retries ``` -------------------------------- ### Retrieve list values with get_list Source: https://context7.com/chimpler/pyhocon/llms.txt Extracts values as a list, including the ability to convert numerically-indexed dictionaries into lists. ```python from pyhocon import ConfigFactory conf = ConfigFactory.parse_string(""" { servers = [ "server1.example.com" "server2.example.com" "server3.example.com" ] ports = [8080, 8081, 8082] # Numerically indexed dictionary (converted to list) indexed { 0 = "first" 1 = "second" 2 = "third" } } """) servers = conf.get_list('servers') # Output: ['server1.example.com', 'server2.example.com', 'server3.example.com'] ports = conf.get_list('ports') # Output: [8080, 8081, 8082] indexed = conf.get_list('indexed') # Output: ['first', 'second', 'third'] ``` -------------------------------- ### Parse HOCON from string Source: https://context7.com/chimpler/pyhocon/llms.txt Parses HOCON content directly from a string, supporting features like environment variable substitution and multi-line strings. ```python from pyhocon import ConfigFactory hocon_content = """ { database { host = "localhost" port = 5432 credentials { username = admin password = ${DB_PASSWORD} # Falls back to environment variable } } # List with optional trailing comma allowed_ips = [ 192.168.1.1 192.168.1.2, ] # Multi-line string welcome_message = """ Welcome to our service! Please login to continue. """ } """ conf = ConfigFactory.parse_string(hocon_content) print(conf['database.host']) # Output: localhost print(conf['database.credentials.username']) # Output: admin print(conf['allowed_ips']) # Output: ['192.168.1.1', '192.168.1.2'] ```