### Install ConfigObj using pip Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Install the latest stable version of ConfigObj using pip. This is the recommended method for installation. ```bash pip install configobj ``` -------------------------------- ### ConfigObj File Format Example Source: https://context7.com/diffsk/configobj/llms.txt An example of an enhanced INI file structure supported by ConfigObj, featuring nested sections, lists, and multiline strings. ```ini # This is the initial comment app_name = MyApplication version = 1.0.0 [database] host = localhost port = 5432 credentials = admin, secretpassword # This is a list value [[connection_pool]] # Nested section for connection pooling min_connections = 5 max_connections = 20 [[[timeouts]]] # Deeply nested section connect = 30 read = 60 [features] enabled_modules = auth, api, dashboard description = '''A multiline value that spans multiple lines. Line breaks are preserved.''' # Final comment at the end of file ``` -------------------------------- ### Define a basic configspec Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Example of a configspec file defining integer, string, and option constraints. ```default port = integer(0, 100) user = string(max=25) mode = option('quiet', 'loud', 'silent') ``` -------------------------------- ### Transform Keys and Values with ConfigObj walk Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md This example demonstrates transforming placeholder keys and values within a ConfigObj using the walk method. It replaces 'XXXX' with 'CLIENT1' in both keys and values. ```python # We use 'XXXX' as a placeholder config = ''' XXXXkey1 = XXXXvalue1 XXXXkey2 = XXXXvalue2 XXXXkey3 = XXXXvalue3 [XXXXsection1] XXXXkey1 = XXXXvalue1 XXXXkey2 = XXXXvalue2 XXXXkey3 = XXXXvalue3 [XXXXsection2] XXXXkey1 = XXXXvalue1 XXXXkey2 = XXXXvalue2 XXXXkey3 = XXXXvalue3 [[XXXXsection1]] XXXXkey1 = XXXXvalue1 XXXXkey2 = XXXXvalue2 XXXXkey3 = XXXXvalue3 '''.splitlines() cfg = ConfigObj(config) # def transform(section, key): val = section[key] newkey = key.replace('XXXX', 'CLIENT1') section.rename(key, newkey) if isinstance(val, (tuple, list, dict)): pass else: val = val.replace('XXXX', 'CLIENT1') section[newkey] = val # cfg.walk(transform, call_on_sections=True) print cfg ConfigObj({'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3', 'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3'}, 'CLIENT1section2': {'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3', 'CLIENT1section1': {'CLIENT1key1': 'CLIENT1value1', 'CLIENT1key2': 'CLIENT1value2', 'CLIENT1key3': 'CLIENT1value3' Р}}) ``` -------------------------------- ### Config File Format Example Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Illustrates the INI-like format supported by ConfigObj, including comments, quoted keys and values, sections, subsections, lists, and multiline values. ```default # This is the 'initial_comment' # Which may be several lines keyword1 = value1 'keyword 2' = 'value 2' [ "section 1" ] # This comment goes with keyword 3 keyword 3 = value 3 'keyword 4' = value4, value 5, 'value 6' [[ sub-section ]] # an inline comment # sub-section is inside "section 1" 'keyword 5' = 'value 7' 'keyword 6' = '''A multiline value, that spans more than one line :-) The line breaks are included in the value.' [[[ sub-sub-section ]]] # sub-sub-section is *in* 'sub-section' # which is in 'section 1' 'keyword 7' = 'value 8' [section 2] # an inline comment keyword8 = "value 9" keyword9 = value10 # an inline comment # The 'final_comment' # Which also may be several lines ``` -------------------------------- ### Integer validation examples Source: https://github.com/diffsk/configobj/blob/release/docs/validate.md Demonstrates usage of the integer validator with optional min and max constraints. ```default integer() integer(3, 9) # any value from 3 to 9 integer(min=0) # any positive value integer(max=9) ``` -------------------------------- ### ConfigObj validation syntax Source: https://github.com/diffsk/configobj/blob/release/docs/validate.md Example of how validation checks appear when used within a ConfigObj configuration. ```default keyword = int_list(max=6) ``` -------------------------------- ### Example usage of get_extra_values Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates how to identify and print extra values or sections found in a validated ConfigObj instance. ```python vtor = validate.Validator() # ini is your config file - cs is the configspec cfg = ConfigObj(ini, configspec=cs) cfg.validate(vtor, preserve_errors=True) for sections, name in get_extra_values(cfg): # this code gets the extra values themselves the_section = cfg for section in sections: the_section = cfg[section] # the_value may be a section or a value the_value = the_section[name] section_or_value = 'value if isinstance(the_value, dict): # Sections are subclasses of dict section_or_value = 'section' section_string = ', '.join(sections) or "top level" print 'Extra entry in section: %s. Entry %r is a %s' % (section_string, name, section_or_value) ``` -------------------------------- ### Get extra values from config Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Displays the signature for the get_extra_values function. ```python get_extra_values(conf) ``` -------------------------------- ### Example usage of flatten_errors Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates how to iterate over and print validation errors returned by flatten_errors. ```python vtor = validate.Validator() # ini is your config file - cs is the configspec cfg = ConfigObj(ini, configspec=cs) res = cfg.validate(vtor, preserve_errors=True) for entry in flatten_errors(cfg, res): # each entry is a tuple section_list, key, error = entry if key is not None: section_list.append(key) else: section_list.append('[missing section]') section_string = ', '.join(section_list) if error == False: error = 'Missing value or section.' print section_string, ' = ', error ``` -------------------------------- ### Define default values in a configspec Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Examples of setting default values within a configspec file for various data types. ```default key1 = integer(0, 30, default=15) key2 = integer(default=15) key3 = boolean(default=True) key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today') ``` -------------------------------- ### Mixed list type specification Source: https://github.com/diffsk/configobj/blob/release/docs/validate.md Examples for defining mixed list structures and specific positional types. ```default int, str, boolean, float, ip_addr ``` ```default mixed_list(str, str, int, int) ``` -------------------------------- ### Create and Write a Config File Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Illustrates creating an empty ConfigObj, setting a filename, adding values, and writing the configuration to a file. ```python from configobj import ConfigObj config = ConfigObj() config.filename = filename ``` -------------------------------- ### Python: Create and Write ConfigObj Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates creating a ConfigObj instance and writing it to a file. This is useful for programmatically generating configuration files. ```python config = ConfigObj() config['keyword1'] = value1 config['keyword2'] = value2 config['section1'] = {} config['section1']['keyword3'] = value3 config['section1']['keyword4'] = value4 section2 = { 'keyword5': value5, 'keyword6': value6, 'sub-section': { 'keyword7': value7 } } config['section2'] = section2 config['section3'] = {} config['section3']['keyword 8'] = [value8, value9, value10] config['section3']['keyword 9'] = [value11, value12, value13] config.write() ``` -------------------------------- ### Manage Application Configuration Lifecycle Source: https://context7.com/diffsk/configobj/llms.txt Demonstrates reloading configuration from disk and resetting the configuration object state. ```python print(f"Running with debug={config['settings']['debug']}") # Later, reload config from disk (e.g., after SIGHUP) try: config.reload() config.validate(validator) print("Configuration reloaded successfully") except Exception as e: print(f"Reload failed: {e}") # Or reset to empty state config.reset() # config is now an empty ConfigObj with no values ``` -------------------------------- ### Instantiate ConfigObj with options Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Use keyword arguments to pass configuration options to the ConfigObj constructor, replacing the deprecated dictionary unpacking method. ```python config = ConfigObj(filename, **options) ``` -------------------------------- ### ConfigObj Constructor Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Instantiating ConfigObj with various options. ```APIDOC ## ConfigObj Constructor ### Description Instantiates a ConfigObj object with specified options. ### Method Constructor ### Endpoint N/A (Python Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **infile**: `None` (default) * Can be a filename, a list of lines, a file-like object, or a dictionary. * If `None`, an empty ConfigObj is created. * If a filename is provided, `file_error` and `create_empty` options determine behavior if the file does not exist. * If a dictionary is provided, keys must be strings, and order is arbitrary. * **raise_errors**: `False` (default) * If `True`, errors are raised immediately during parsing. * If `False`, a single error is raised at the end of parsing. * Altering this value after initial parsing has no effect. * **list_values**: `True` (default) * If `True`, list values are parsed. * If `False`, values are not parsed for lists, and single-line values are not quoted. * Affects whether single-line values are quoted when writing. * **create_empty**: `False` (default) * If `True` and `infile` does not exist, an empty file is created. * Altering this value after initial parsing has no effect. * **file_error**: `False` (default) * If `True` and `infile` does not exist, an `IOError` is raised. * Raised during constructor or `reload` method. * **interpolation**: `True` (default) * Enables string interpolation for values. * Interpolation is also done in list values (new in 4.7.0). * **configspec**: `None` (default) * A filename or list of lines specifying validation rules. * Used for type conversion and value checking. * **stringify**: `True` (default) * If `True`, non-string values are converted to strings when writing. * If `False`, attempting to set a non-string value raises a `TypeError`. * **indent_type**: `' '` (default) * Specifies the indentation string for output (e.g., `' '`, `' '`, `''`). * If not specified and initialized with a dictionary, defaults to four spaces. * If not specified and initialized with lines or a file, uses indentation from the first indented line. ### Request Example ```python from configobj import ConfigObj # Example with filename and options config = ConfigObj('settings.ini', raise_errors=True, list_values=False) # Example initializing from a dictionary options_dict = {'key1': 'value1', 'key2': 'value2'} config_from_dict = ConfigObj(options_dict) # Example with unpacking options dictionary (deprecated) options = {'raise_errors': True} config_deprecated = ConfigObj('settings.ini', **options) ``` ### Response #### Success Response (200) N/A (Constructor returns an object) #### Response Example ```python # Example of a created ConfigObj instance # config = ``` ``` -------------------------------- ### Basic Configobj Type Conversions Source: https://context7.com/diffsk/configobj/llms.txt Demonstrates basic type conversions using configobj's as_float and as_list methods. Ensure values are of the expected type or wrapped appropriately. ```python timeout = config['server'].as_float('timeout') # 30.5 # Ensure value is a list (wraps single values in a list) hosts = config['server'].as_list('hosts') # ['localhost'] ``` -------------------------------- ### Load a ConfigObj instance as a configspec Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates loading a configspec file using specific parameters required for correct parsing. ```python from configobj import ConfigObj configspec = ConfigObj(configspecfilename, encoding='UTF8', list_values=False, _inspec=True) config = ConfigObj(filename, configspec=configspec) ``` -------------------------------- ### Basic Keyword Syntax Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Illustrates the fundamental structure for defining keywords, values, and inline comments in a configuration file. ```default # comment line # comment line keyword = value # inline comment ``` -------------------------------- ### Section Header Syntax Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Explains how to define new sections within a configuration file using square brackets for the section name. Comments can precede and follow the section marker. ```default # The First Section [ section name 1 ] # first section keyword1 = value1 ``` -------------------------------- ### Read a Config File Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates the basic usage of ConfigObj to read a configuration file. The filename is passed to the ConfigObj constructor. ```python from configobj import ConfigObj config = ConfigObj(filename) ``` -------------------------------- ### ConfigObj Constructor Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Shows the signature for the ConfigObj constructor, highlighting various keyword arguments that can be used to customize its behavior during initialization. ```python config = ConfigObj(infile=None, options=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False) ``` -------------------------------- ### Write Configuration Files Programmatically Source: https://context7.com/diffsk/configobj/llms.txt Create or modify configuration files by assigning values and dictionaries to a ConfigObj instance. ```python from configobj import ConfigObj # Create a new config config = ConfigObj() config.filename = 'output.ini' # Add simple values config['app_name'] = 'MyApplication' config['version'] = '1.0.0' # Create sections config['database'] = {} config['database']['host'] = 'localhost' config['database']['port'] = '5432' config['database']['name'] = 'myapp_db' # Create nested sections using a dictionary config['logging'] = { 'level': 'INFO', 'format': '%(asctime)s - %(message)s', 'handlers': { 'file': { 'path': '/var/log/myapp.log', 'max_size': '10MB' }, 'console': { 'enabled': 'true' } } } # Add list values config['allowed_hosts'] = ['localhost', '127.0.0.1', '*.example.com'] # Write to file config.write() ``` -------------------------------- ### write(file_object=None) Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Writes the current ConfigObj instance to a file or returns a list of lines. ```APIDOC ## write(file_object=None) ### Description Writes the current ConfigObj configuration to a file-like object or returns the configuration as a list of lines if no file object is provided. ### Parameters #### Request Body - **file_object** (file-like object) - Optional - A file-like object to write the configuration to. If None, the method returns a list of lines. ### Response #### Success Response (200) - **Return Value** (list or None) - Returns a list of lines if file_object is None, otherwise writes to the provided object. ``` -------------------------------- ### List Value Syntax Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates how to represent lists as values, including single-member lists with trailing commas and empty lists. ```default keyword1 = value1, value2, value3 keyword2 = value1, # a single member list keyword3 = , # an empty list ``` -------------------------------- ### ConfigObj Methods Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Reference for the core methods available in ConfigObj. ```APIDOC ## ConfigObj Methods ### `write()` Writes the configuration object to a file. ### `validate(configspec)` Validates the configuration object against a given configspec. #### Return Value Returns a list of errors found during validation. #### Mentioning Default Values Allows specifying default values for configuration options. #### Mentioning Repeated Sections and Values Supports validation of repeated sections and values. #### Mentioning SimpleVal Handles validation of simple values. #### Mentioning copy Mode Supports a 'copy' mode for validation. ### `reload()` Reloads the configuration from the file. ### `reset()` Resets the configuration object to its default state. ``` -------------------------------- ### Copying a ConfigObj Instance Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates how to copy a ConfigObj instance. Note that this method only copies members and not attributes or comments. Since version 4.7.0, the order of members and sections is preserved. ```python # only copies members # not attributes/comments config2 = ConfigObj(config1) ``` -------------------------------- ### Writing ConfigObj to a File Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Use the `write` method to save the current ConfigObj to a file-like object or return a list of lines if no file object is provided. The `filename` attribute determines the output destination. ```python write(file_object=None) ``` -------------------------------- ### Validator instantiation methods Source: https://github.com/diffsk/configobj/blob/release/docs/validate.md Shows how to instantiate a Validator with or without a custom function dictionary. ```python from validate import Validator vtor = Validator() ``` ```python from validate import Validator # fdict = { 'check_name1': function1, 'check_name2': function2, 'check_name3': function3, } # vtor = Validator(fdict) ``` -------------------------------- ### Method: reset Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Restores a ConfigObj instance to a freshly created state. ```APIDOC ## reset ### Description Restores a ConfigObj instance to a freshly created state. This method takes no arguments and returns nothing. ``` -------------------------------- ### Attributes Overview Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Key attributes available on a ConfigObj instance. ```APIDOC ## ConfigObj Attributes ### Attributes - **indent_type** - **interpolation** (boolean) - Controls string interpolation. - **stringify** (boolean) - If True, validate changes values to strings. - **BOM** (boolean) - Indicates if the file started with a Byte Order Mark. - **initial_comment** (list) - Lines of comments before members. - **final_comment** (list) - **list_values** - **encoding** - **default_encoding** - **unrepr** - **write_empty_values** - **newlines** ``` -------------------------------- ### ConfigObj Reload and Reset Methods Source: https://context7.com/diffsk/configobj/llms.txt Utilize `reload()` to re-read configuration from disk and `reset()` to revert to a fresh state. These methods are essential for long-running applications needing to apply configuration changes dynamically. ```python from configobj import ConfigObj from validate import Validator # Initial load with validation config = ConfigObj('app.ini', configspec='app.spec') validator = Validator() config.validate(validator) ``` -------------------------------- ### Represent configuration as a Python dictionary Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Shows the resulting Python data structure after parsing a nested configuration file. ```python ConfigObj({ 'keyword1': 'value1', 'keyword2': 'value2', 'section 1': { 'keyword1': 'value1', 'keyword2': 'value2', 'sub-section': { 'keyword1': 'value1', 'keyword2': 'value2', 'nested section': { 'keyword1': 'value1', 'keyword2': 'value2', }, }, 'sub-section2': { 'keyword1': 'value1', 'keyword2': 'value2', }, 'sub-section3': { 'keyword1': 'value1', 'keyword2': 'value2', }, }, }) ``` -------------------------------- ### Access Config Values Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Shows how to access values and subsections from a loaded ConfigObj instance, treating it like a dictionary. ```python from configobj import ConfigObj config = ConfigObj(filename) # value1 = config['keyword1'] value2 = config['keyword2'] # section1 = config['section1'] value3 = section1['keyword3'] value4 = section1['keyword4'] # # you could also write value3 = config['section1']['keyword3'] value4 = config['section1']['keyword4'] ``` -------------------------------- ### ConfigObj Type Conversion Methods Source: https://context7.com/diffsk/configobj/llms.txt Sections provide `as_bool`, `as_int`, `as_float`, and `as_list` for convenient type conversion of string values without using the validation system. These methods offer flexibility in parsing common data types. ```python from configobj import ConfigObj config = ConfigObj({ 'server': { 'port': '8080', 'workers': '4', 'debug': 'true', 'timeout': '30.5', 'hosts': 'localhost' # Single value, not a list } }) # Convert to boolean (accepts true/false, yes/no, on/off, 1/0) debug = config['server'].as_bool('debug') # True # Convert to integer port = config['server'].as_int('port') # 8080 workers = config['server'].as_int('workers') # 4 ``` -------------------------------- ### ConfigObj Section Methods: merge, walk, dict Source: https://context7.com/diffsk/configobj/llms.txt Sections in ConfigObj offer methods for recursive merging of configurations, applying a function to all values using `walk`, and converting a ConfigObj section into a plain dictionary with `dict`. ```python from configobj import ConfigObj # Merge: recursively update config with another config defaults = ConfigObj({ 'database': {'host': 'localhost', 'port': 5432}, 'cache': {'enabled': True, 'ttl': 3600} }) user_config = ConfigObj({ 'database': {'host': 'production-db.example.com'}, 'cache': {'ttl': 7200} }) defaults.merge(user_config) # defaults now has user values merged in print(defaults['database']['host']) # production-db.example.com print(defaults['database']['port']) # 5432 (from defaults) print(defaults['cache']['ttl']) # 7200 (overridden) # Walk: apply a function to all values def uppercase_values(section, key): val = section[key] if isinstance(val, str): section[key] = val.upper() config = ConfigObj({'name': 'test', 'section': {'value': 'hello'}}) config.walk(uppercase_values) print(config['name']) # TEST print(config['section']['value']) # HELLO # dict: convert to plain dictionary (deep copy) config = ConfigObj('settings.ini') plain_dict = config.dict() # Returns a regular dict, not ConfigObj ``` -------------------------------- ### Writing Empty Values in ConfigObj Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates how to configure ConfigObj to write empty strings as empty values in configuration files. Set `write_empty_values` to `True`. ```python from configobj import ConfigObj cfg = ''' key = key2 = # a comment '''.splitlines() config = ConfigObj(cfg) print config ConfigObj({'key': '', 'key2': ''}) config.write_empty_values = True for line in config.write(): print line key = key2 = # a comment ``` -------------------------------- ### Define nested sections in configuration Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Demonstrates the use of square brackets to define hierarchical sections and sub-sections within a configuration file. ```default # The Second Section [ "section name 2" ] # second section keyword2 = value2 ``` ```default # initial comment keyword1 = value1 keyword2 = value2 [section 1] keyword1 = value1 keyword2 = value2 [[sub-section]] # this is in section 1 keyword1 = value1 keyword2 = value2 [[[nested section]]] # this is in sub section keyword1 = value1 keyword2 = value2 [[sub-section2]] # this is in section 1 again keyword1 = value1 keyword2 = value2 [[sub-section3]] # this is also in section 1, indentation is misleading here keyword1 = value1 keyword2 = value2 # final comment ``` -------------------------------- ### Method: reload Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Reloads a ConfigObj instance from the filesystem, reusing the original configspec. ```APIDOC ## reload ### Description If a ConfigObj instance was loaded from the filesystem, this method reloads it. It reuses any configspec supplied at instantiation. ### Method Method call ### Errors - **ReloadError**: Raised if the ConfigObj does not have a filename attribute pointing to a file. ``` -------------------------------- ### Initialize ConfigObj with manual configspec Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Create a configspec object with interpolation disabled to prevent processing within the spec file. ```python from configobj import ConfigObj configspec = ConfigObj(spec_filename, interpolation=False, list_values=False, _inspec=True) conf = ConfigObj(config_filename, configspec=configspec) ``` -------------------------------- ### ConfigObj File Format Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Description of the format used for configuration files. ```APIDOC ## The Config File Format ### Sections Configuration is organized into sections, denoted by square brackets `[]`. #### Section Attributes Attributes can be set within sections. #### Section Methods Sections may have associated methods. #### Walking a Section Iterating through the contents of a section. ### Examples Illustrative examples of config file structure. ``` -------------------------------- ### SimpleVal Configuration Presence Check Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Use SimpleVal to verify that all expected keys are present in a configuration file without performing full type validation. ```default # config file for an application port = 80 protocol = http domain = voidspace top_level_domain = org.uk ``` ```default port = '' protocol = '' domain = '' top_level_domain = '' ``` ```python config = Configobj(filename, configspec=configspec) val = SimpleVal() test = config.validate(val) if test == True: print 'All values present.' elif test == False: print 'No values present!' else: for entry in test: if test[entry] == False: print '"%s" missing.' % entry ``` -------------------------------- ### Read Configuration Files with ConfigObj Source: https://context7.com/diffsk/configobj/llms.txt Access configuration values using standard dictionary syntax, including support for nested sections. ```python from configobj import ConfigObj # Read config from a file config = ConfigObj('settings.ini') # Access values using dictionary syntax database_host = config['database']['host'] database_port = config['database']['port'] debug_mode = config['settings']['debug'] # Iterate over sections for section in config: print(f"Section: {section}") for key in config[section]: print(f" {key} = {config[section][key]}") # Access nested subsections api_timeout = config['services']['api']['timeout'] ``` -------------------------------- ### Generate Default Config Files with Copy Mode Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Use copy=True during validation to write default values and comments from the configspec into the output file. ```python from configobj import ConfigObj from validate import Validator vdt = Validator() config = ConfigObj(configspec='default.ini') config.filename = 'new_default.ini' config.validate(vdt, copy=True) config.write() ``` -------------------------------- ### Create a new section from a dictionary Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Illustrates that assigning a dictionary to a ConfigObj creates a new Section object, which is a copy rather than a reference. ```python config = ConfigObj() vals = {'key1': 'key 1', 'key2': 'key 2' } config['vals'] = vals config['vals'] == vals True config['vals'] is vals False ``` -------------------------------- ### Validator Initialization Source: https://github.com/diffsk/configobj/blob/release/docs/validate.md Instantiating the Validator class with optional custom functions. ```APIDOC ## Validator Initialization ### Description Creates a new Validator instance. Optionally accepts a dictionary of custom check functions. ### Parameters - **fdict** (dict) - Optional - A dictionary mapping check names to custom function objects. ### Request Example ```python from validate import Validator fdict = {'check_name1': function1} vtor = Validator(fdict) ``` ``` -------------------------------- ### Apply Default Values and Comments with ConfigObj Source: https://context7.com/diffsk/configobj/llms.txt Utilize `copy=True` during validation to incorporate default values and comments from a configspec into the configuration file. This is useful for generating configuration files with sensible defaults. ```python from configobj import ConfigObj from validate import Validator # Configspec with defaults configspec = """ [server] host = string(default='0.0.0.0') port = integer(default=8080) ssl_enabled = boolean(default=False) [cache] # Cache configuration backend = option('memory', 'redis', 'memcached', default='memory') ttl = integer(default=3600) max_size = integer(default=1000) """.splitlines() # Create config (file may not exist or be empty) config = ConfigObj(configspec=configspec) config.filename = 'default_config.ini' validator = Validator() # copy=True includes defaults and comments in output config.validate(validator, copy=True) config.write() # Generated file will contain all defaults with comments ``` -------------------------------- ### ConfigObj Attributes Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Reference for the attributes that can be set on a ConfigObj instance. ```APIDOC ## ConfigObj Attributes ### `interpolation` (string) Controls string interpolation behavior. ### `stringify` (boolean) Determines if values should be stringified. ### `BOM` (string) Specifies the Byte Order Mark encoding. ### `initial_comment` (list of strings) Stores initial comments in the configuration file. ### `final_comment` (list of strings) Stores final comments in the configuration file. ### `list_values` (list of strings) Defines values that should be treated as lists. ### `encoding` (string) Specifies the encoding for reading/writing files. ### `default_encoding` (string) Sets the default encoding if not specified. ### `unrepr` (boolean) Enables/disables unrepresentation mode. ### `write_empty_values` (boolean) Controls whether empty values are written to the file. ### `newlines` (string) Specifies the newline character(s) to use. ``` -------------------------------- ### Merge User Settings into Default Config Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Use the merge method to recursively update a default configuration with user-specific settings. User settings will overwrite default values where conflicts exist. ```python cfg = ConfigObj(def_cfg) usr = ConfigObj(user_cfg) # cfg.merge(usr) ``` -------------------------------- ### Multi-line Value Syntax Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Shows how to define values that span multiple lines using triple quotes. This method also handles values containing both single and double quotes. ```default keyword1 = ''' A multi line value on several lines''' # with a comment keyword2 = '''I won't be "afraid". ``` ```default keyword3 = """ A multi line value on several lines""" # with a comment keyword4 = """I won't be "afraid". ``` -------------------------------- ### Section Default Restoration Methods Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Methods for restoring default values for keys or recursively for all members. ```APIDOC ## restore_default(key) ### Description Restore (and return) the default value for the specified key. This method will only work for a ConfigObj that was created with a configspec and has been validated. If there is no default value for this key, `KeyError` is raised. ### Method `restore_default(key)` ### Parameters #### Path Parameters - **key** (string) - Required - The key whose default value should be restored. ### Response #### Success Response (200) - **value** (any) - The restored default value for the key. #### Error Response (404) - **KeyError**: Raised if there is no default value for the specified key. ``` ```APIDOC ## restore_defaults() ### Description Recursively restore default values to all members that have them. This method will only work for a ConfigObj that was created with a configspec and has been validated. It doesn’t delete or modify entries without default values. ### Method `restore_defaults()` ### Response #### Success Response (200) - **None** - This method modifies the ConfigObj in place and does not return a value. ``` -------------------------------- ### Using Unrepr Mode in ConfigObj Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Illustrates the `unrepr` mode in ConfigObj for storing and retrieving basic Python data types. Note that inline comments are not saved in this mode. ```python ['A List', 'With', 'Strings'] ``` ```python "Must be quoted." ``` ```python "The backslash must be escaped \\" ``` -------------------------------- ### Section Walking Method Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Method for recursively applying a function to every member of a section. ```APIDOC ## walk(function, raise_errors=True, call_on_sections=False, **keywargs) ### Description This method can be used to transform values and names. It walks through every member and calls a function on the keyword and value. It walks recursively through subsections. It returns a dictionary of all the computed values. If the function raises an exception, the default is to propagate the error, and stop. If `raise_errors=False` then it sets the return value for that keyword to `False` instead, and continues. If `call_on_sections` is `True`, the function is called on subsections before recursing into them. ### Method `walk(function, raise_errors=True, call_on_sections=False, **keywargs)` ### Parameters #### Path Parameters - **function** (callable) - Required - The function to call on each member. It receives `(section, key)` as arguments. - **raise_errors** (boolean) - Optional - If `False`, exceptions raised by the function are caught and the return value is set to `False`. - **call_on_sections** (boolean) - Optional - If `True`, the function is also called on subsections before recursing into them. - **keywargs** - Optional - Additional keyword arguments to pass to the function. ### Response #### Success Response (200) - **dictionary** (dict) - A dictionary of all the computed values from the applied function. ``` -------------------------------- ### ConfigObj Validation Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Details on how to use configspec for validating configuration files. ```APIDOC ## ConfigObj Validation ### `configspec` A configuration specification file used for validation. ### Type Conversion ConfigObj automatically handles type conversion based on the configspec. ### Default Values Allows defining default values for configuration options within the configspec. #### List Values Specific handling for default values of list types. ### Repeated Sections Supports validation of sections that can appear multiple times. ### Repeated Values Supports validation of values that can appear multiple times within a section. ### Copy Mode A mode for validation that allows copying values from other sections. ### Validation and Interpolation Interaction between validation rules and string interpolation. ### Extra Values Handling of values present in the config file but not defined in the configspec. ### SimpleVal Validation of simple, scalar values. ``` -------------------------------- ### Validate presence with SimpleVal Source: https://github.com/diffsk/configobj/blob/release/docs/configobj.md Use SimpleVal to verify that all required members are present in the configuration without enforcing specific types. ```python val = SimpleVal() test = config.validate(val) if test is True: print 'Succeeded.' ``` -------------------------------- ### String Interpolation in ConfigObj Source: https://context7.com/diffsk/configobj/llms.txt ConfigObj supports string interpolation using `%(name)s` or Template-style `${name}` syntax. This allows values to reference other values within the configuration. ```python from configobj import ConfigObj config_content = """ [paths] base_dir = /opt/myapp log_dir = %(base_dir)s/logs data_dir = %(base_dir)s/data config_dir = %(base_dir)s/config [database] host = localhost port = 5432 connection_string = postgresql://%(host)s:%(port)s/mydb [DEFAULT] # Values in DEFAULT are available to all sections app_name = MyApplication """.splitlines() config = ConfigObj(config_content, interpolation=True) # Interpolated values are resolved when accessed print(config['paths']['log_dir']) # /opt/myapp/logs print(config['paths']['data_dir']) # /opt/myapp/data print(config['database']['connection_string']) # postgresql://localhost:5432/mydb # Template-style interpolation (use interpolation='template') config2 = ConfigObj(interpolation='template') config2['base'] = '/var/www' config2['static'] = '${base}/static' print(config2['static']) # /var/www/static ```