### Configuration String Example Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Example configuration content as a string. ```ini [metadata] author = Ada Lovelace summary = The Analytical Engine ``` -------------------------------- ### Install ConfigUpdater Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Install the package using pip. ```bash pip install configupdater ``` -------------------------------- ### Install ConfigUpdater Source: https://context7.com/pyscaffold/configupdater/llms.txt Install the library using common package managers. ```bash # Using pip pip install configupdater # Using conda conda install -c conda-forge configupdater ``` -------------------------------- ### Clone and Install Repository Source: https://github.com/pyscaffold/configupdater/blob/main/CONTRIBUTING.rst Commands to clone the project fork and install it in development mode. ```bash git clone git@github.com:YourLogin/configupdater.git ``` ```bash python setup.py develop ``` -------------------------------- ### Install ConfigUpdater Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Install the ConfigUpdater package using pip or conda. ```bash pip install configupdater ``` ```bash conda install -c conda-forge configupdater ``` -------------------------------- ### Define Configuration String Source: https://github.com/pyscaffold/configupdater/blob/main/README.md Example configuration content stored as a string for testing or manipulation. ```python cfg = """ [metadata] author = Ada Lovelace summary = The Analytical Engine """ ``` -------------------------------- ### Setup Development Environment Source: https://github.com/pyscaffold/configupdater/blob/main/CONTRIBUTING.rst Commands to create and activate a dedicated Conda environment for development. ```bash conda create -n configupdater python=3 virtualenv pytest pytest-cov ``` ```bash source activate configupdater ``` -------------------------------- ### Configure Pre-commit Hooks Source: https://github.com/pyscaffold/configupdater/blob/main/CONTRIBUTING.rst Commands to install pre-commit and initialize the project's automated code quality checks. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install ConfigUpdater in Develop Mode Source: https://github.com/pyscaffold/configupdater/blob/main/docs/contributing.md Install the ConfigUpdater package in development mode after cloning the repository. This allows for direct code changes to be reflected without reinstallation. ```default python setup.py develop ``` -------------------------------- ### GET /config/section Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Retrieves an entire section by its name. ```APIDOC ## GET /config/section ### Description Retrieves an entire section by its name, similar to dict.get(). ### Parameters #### Query Parameters - **name** (str) - Required - The name of the section. - **default** (any) - Optional - Value to return if the section is not found. ``` -------------------------------- ### GET /config/check Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Utility methods to check for the existence of sections or options. ```APIDOC ## GET /config/check ### Description Checks for the existence of sections or options within the configuration. ### Parameters #### Query Parameters - **section** (str) - Required - Name of section. - **option** (str) - Optional - Name of option. ``` -------------------------------- ### Activate Conda Environment Source: https://github.com/pyscaffold/configupdater/blob/main/docs/contributing.md Activate the 'configupdater' Conda environment before starting development to ensure all dependencies are correctly loaded. ```default source activate configupdater ``` -------------------------------- ### GET /config/option Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Retrieves a specific option from a section. Note that this method behaves differently from standard dict.get() and requires section and option arguments. ```APIDOC ## GET /config/option ### Description Retrieves a nested Option object from a specified section. If the option is not found, a fallback value can be returned. ### Parameters #### Query Parameters - **section** (str) - Required - The name of the section. - **option** (str) - Required - The name of the option. - **fallback** (T) - Optional - Value to return if the option is not found. ### Response - **Returns** (Option/T) - Returns an Option object if found, otherwise the fallback value. ``` -------------------------------- ### Add sections and options with formatting Source: https://context7.com/pyscaffold/configupdater/llms.txt Demonstrates adding sections, options, comments, and blank lines using the block builder pattern. ```python ( updater["metadata"] .add_after.space(2) .comment("Build configuration") .section("build") ) updater["build"]["target"] = "wheel" print(updater) ``` ```python ( updater["build"]["target"] .add_after .comment("Output directory") .option("dist_dir", "dist") .space(1) .comment("Enable optimization") .option("optimize", "2") ) print(updater) ``` -------------------------------- ### Read Configuration File Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Initialize ConfigUpdater and read a configuration file. ```python from configupdater import ConfigUpdater updater = ConfigUpdater() updater.read("setup.cfg") ``` -------------------------------- ### Writing and Updating Configuration Files Source: https://context7.com/pyscaffold/configupdater/llms.txt Demonstrates how to update configuration values and write them back to a file, a string buffer, or a new file. Use `update_file()` for in-place updates (if read from file) or `write()` to a file-like object. ```python from configupdater import ConfigUpdater import io cfg = """ [metadata] name = myproject version = 1.0.0 """ updater = ConfigUpdater() updater.read_string(cfg) updater["metadata"]["version"].value = "2.0.0" # Method 1: Update the original file (only works if read from file) # updater.update_file() # Method 2: Write to a new file with open("new_config.cfg", "w") as f: updater.write(f) # Method 3: Write to a string buffer buffer = io.StringIO() updater.write(buffer, validate=True) # validate=True checks with ConfigParser output = buffer.getvalue() print(output) # Output: # [metadata] # name = myproject # version = 2.0.0 # Disable validation if needed (for non-standard formats) buffer2 = io.StringIO() updater.write(buffer2, validate=False) ``` -------------------------------- ### Display Resulting Configuration Source: https://github.com/pyscaffold/configupdater/blob/main/README.md The output format after adding a new option. ```ini [metadata] author = Ada Lovelace summary = The Analytical Engine license = MIT ``` -------------------------------- ### Querying Sections and Options in ConfigUpdater Source: https://context7.com/pyscaffold/configupdater/llms.txt Learn how to check for the existence of sections and options, list them, iterate through them, and retrieve values with fallbacks. This is useful for validating configuration structure and accessing specific settings. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject version = 1.0.0 author = Ada Lovelace [options] packages = find: python_requires = >=3.7 """ updater = ConfigUpdater() updater.read_string(cfg) # Check if section exists print(f"Has metadata: {updater.has_section('metadata')}") # Output: Has metadata: True print(f"Has missing: {updater.has_section('missing')}") # Output: Has missing: False # Check if option exists print(f"Has author: {updater.has_option('metadata', 'author')}") # Output: Has author: True # List all section names print(f"Sections: {updater.sections()}") # Output: Sections: ['metadata', 'options'] # List options in a section print(f"Options in metadata: {updater.options('metadata')}") # Output: Options in metadata: ['name', 'version', 'author'] # Iterate over sections for section in updater.iter_sections(): print(f"Section: {section.name}") for option in section.iter_options(): print(f" {option.key} = {option.value}") # Get option with fallback license_opt = updater.get("metadata", "license", fallback="Unknown") print(f"License: {license_opt}") # Output: License: Unknown # Get section with default missing_section = updater.get_section("missing", default=None) print(f"Missing section: {missing_section}") # Output: Missing section: None ``` -------------------------------- ### Resulting Configuration with Comment Source: https://github.com/pyscaffold/configupdater/blob/main/README.md The output format after adding a comment and option. ```ini [metadata] author = Ada Lovelace # Ada would have loved MIT license = MIT summary = Analytical Engine calculating the Bernoulli numbers ``` -------------------------------- ### Configuration State After Adding License Before Summary Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md The configuration file state after adding 'license' before 'summary' with a comment. ```ini [metadata] author = Ada Lovelace # Ada would have loved MIT license = MIT summary = Analytical Engine calculating the Bernoulli numbers ``` -------------------------------- ### Configuration State After Adding License Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md The configuration file state after adding the 'license' option. ```ini [metadata] author = Ada Lovelace summary = The Analytical Engine license = MIT ``` -------------------------------- ### Configuration State After Adding License After Author Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md The configuration file state after adding 'license' after 'author' with a comment. ```ini [metadata] author = Ada Lovelace # Ada would have loved MIT license = MIT summary = The Analytical Engine ``` -------------------------------- ### Configuration State After Adding Options Section Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md The configuration file state after adding an 'options' section before 'metadata' with a comment and spacing. ```ini [metadata] author = Ada Lovelace summary = The Analytical Engine # Some specific project options [options] ``` -------------------------------- ### Read and Update Configuration Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Initialize ConfigUpdater, read a configuration file, and modify an existing key's value. The original file formatting is preserved. ```python from configupdater import ConfigUpdater updater = ConfigUpdater() updater.read("setup.cfg") updater["metadata"]["author"].value = "Alan Turing" print(updater) ``` -------------------------------- ### Resulting configuration structure Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md The expected output format after injecting the build_sphinx section. ```default [metadata] author = Ada Lovelace summary = The Analytical Engine [build_sphinx] source_dir = docs build_dir = docs/_build ``` -------------------------------- ### Read Configuration Files Source: https://context7.com/pyscaffold/configupdater/llms.txt Load configuration data from files, strings, or file-like objects. ```python from configupdater import ConfigUpdater # Read from a file updater = ConfigUpdater() updater.read("setup.cfg") # Read from a string cfg_string = """ [metadata] name = myproject version = 1.0.0 author = John Doe [options] packages = find: python_requires = >=3.7 """ updater = ConfigUpdater() updater.read_string(cfg_string) # Read from a file-like object with open("config.ini", "r") as f: updater = ConfigUpdater() updater.read_file(f) # Print the current state of the configuration print(updater) ``` -------------------------------- ### Define a new section as a string Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Define a configuration section structure using a multi-line string for declarative injection. ```default sphinx_sect_str = """ [build_sphinx] source_dir = docs build_dir = docs/_build """ ``` -------------------------------- ### Work with Multi-line Values Source: https://context7.com/pyscaffold/configupdater/llms.txt Handles multi-line configuration values using `as_list()`, `append()`, and `set_values()`. `as_list()` reads the value as a list, `append()` adds an item, and `set_values()` replaces the entire value with a new list, allowing control over formatting. ```python from configupdater import ConfigUpdater cfg = """ [options] install_requires = requests>=2.25.0 numpy>=1.20.0 """ updater = ConfigUpdater() updater.read_string(cfg) # Read multi-line value as a list deps = updater["options"]["install_requires"].as_list() print(f"Dependencies: {deps}") # Append a new value to the multi-line option updater["options"]["install_requires"].append("pandas>=1.3.0") print(updater["options"]["install_requires"].as_list()) ``` ```python # Set a completely new list of values updater["options"]["install_requires"].set_values([ "requests>=2.28.0", "numpy>=1.24.0", "pandas>=2.0.0", "scipy>=1.10.0" ]) print(updater) ``` ```python # Control formatting with set_values options updater2 = ConfigUpdater() updater2.read_string("[options]\npackages =\n") updater2["options"]["packages"].set_values( ["mypackage", "mypackage.utils", "mypackage.core"], separator="\n", indent=" ", prepend_newline=True ) print(updater2) ``` -------------------------------- ### Print Current Configuration State Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Display the current state of the configuration object. ```python print(updater) ``` -------------------------------- ### POST /config/read Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Methods for reading configuration data from various sources. ```APIDOC ## POST /config/read ### Description Parses configuration data from a file, file-like object, or string. ### Parameters #### Request Body - **filename** (str) - Optional - Path to file for read(). - **f** (Iterable) - Optional - File-like object for read_file(). - **string** (str) - Optional - Configuration string for read_string(). - **encoding** (str) - Optional - Encoding for file operations. ``` -------------------------------- ### Run Unit Tests Source: https://github.com/pyscaffold/configupdater/blob/main/CONTRIBUTING.rst Command to execute the project's test suite to ensure changes do not introduce regressions. ```bash python setup.py test ``` -------------------------------- ### Clone ConfigUpdater Repository Source: https://github.com/pyscaffold/configupdater/blob/main/docs/contributing.md Clone your forked copy of the ConfigUpdater repository to your local machine. Replace 'YourLogin' with your GitHub username. ```default git clone git@github.com:YourLogin/configupdater.git ``` -------------------------------- ### Converting ConfigUpdater to a Python Dictionary Source: https://context7.com/pyscaffold/configupdater/llms.txt Transform your configuration data into a standard Python dictionary for easier manipulation or integration with other libraries. This can be done for the entire configuration or for individual sections. ```python from configupdater import ConfigUpdater import json cfg = """ [metadata] name = myproject version = 1.0.0 author = Ada Lovelace [options] packages = find: python_requires = >=3.7 """ updater = ConfigUpdater() updater.read_string(cfg) # Convert entire config to dictionary config_dict = updater.to_dict() print(json.dumps(config_dict, indent=2)) # Output: # { # "metadata": { # "name": "myproject", # "version": "1.0.0", # "author": "Ada Lovelace" # }, # "options": { # "packages": "find:", # "python_requires": ">=3.7" # } # } # Convert single section to dictionary metadata_dict = updater["metadata"].to_dict() print(metadata_dict) # Output: {'name': 'myproject', 'version': '1.0.0', 'author': 'Ada Lovelace'} ``` -------------------------------- ### Inject Section using deepcopy() Source: https://context7.com/pyscaffold/configupdater/llms.txt Copy a section from one ConfigUpdater instance to another using `deepcopy()`. This preserves the section in the source updater. ```python from configupdater import ConfigUpdater from copy import deepcopy # Define a section in a separate string sphinx_config = """ [build_sphinx] source_dir = docs build_dir = docs/_build warning_is_error = true """ # Main configuration main_config = """ [metadata] name = myproject version = 1.0.0 """ # Parse both configurations sphinx_updater2 = ConfigUpdater() sphinx_updater2.read_string(sphinx_config) main_updater2 = ConfigUpdater() main_updater2.read_string(main_config) ( main_updater2["metadata"] .add_after.space(1) .section(deepcopy(sphinx_updater2["build_sphinx"])) ) # Both sphinx_updater2 and main_updater2 now have the build_sphinx section ``` -------------------------------- ### ConfigUpdater Class Methods Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Details on methods available for interacting with configuration options and blocks. ```APIDOC ## ConfigUpdater Methods ### items() **Description**: Returns a list of (name, option) tuples for each option in this section. **Returns**: list of (name, Option) tuples **Return type**: list ### iter_blocks() **Description**: Iterate over all blocks inside the container. ### iter_options() **Description**: Iterate only over option blocks. ### keys() **Description**: Returns a set-like object providing a view on the keys. ### option_blocks() **Description**: Returns option blocks. **Returns**: list of Option blocks **Return type**: list ### options() **Description**: Returns option names. **Returns**: list of option names as strings **Return type**: list ### pop(k) **Description**: Removes specified key and returns the corresponding value. If key is not found, returns the default value if given, otherwise raises KeyError. ### popitem() **Description**: Removes and returns some (key, value) pair as a 2-tuple. Raises KeyError if the dictionary is empty. ### set(option, value) **Description**: Sets an option for chaining. **Parameters**: - **option** (str) - The name of the option. - **value** (None | str | Iterable[str], optional) - The value to set. Defaults to None. ### setdefault(k) **Description**: Returns D.get(k, d) and also sets D[k] = d if k is not in D. ### to_dict() **Description**: Transforms the configuration to a dictionary. **Returns**: A dictionary with the same content. **Return type**: dict ### update(**F) **Description**: Updates the configuration from a mapping/iterable and keyword arguments. **Parameters**: - **&&F**: Keyword arguments to update the configuration. ### *property* name *: str* **Description**: The name of the section. ### *property* next_block *: Block | None* **Description**: The next block in the current container. ### *property* previous_block *: Block | None* **Description**: The previous block in the current container. ### *property* raw_comment **Description**: The raw comment (including the comment mark) inline with the section header. ### *property* updated *: bool* **Description**: True if the option was changed/updated, otherwise False. ``` -------------------------------- ### Insert Options at Specific Positions Source: https://context7.com/pyscaffold/configupdater/llms.txt Use add_before and add_after to insert options or comments at precise locations. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject author = Ada Lovelace summary = The Analytical Engine """ updater = ConfigUpdater() updater.read_string(cfg) # Insert license before summary with a comment ( updater["metadata"]["summary"] .add_before.comment("License information") .option("license", "MIT") ) print(updater) # Insert version after name updater2 = ConfigUpdater() updater2.read_string(cfg) ( updater2["metadata"]["name"] .add_after.option("version", "1.0.0") ) print(updater2) ``` -------------------------------- ### File I/O and Serialization Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Methods for updating files, writing configurations, and transforming data structures. ```APIDOC ## update_file(validate=True) ### Description Update the read-in configuration file. ### Parameters #### Query Parameters - **validate** (Boolean) - Optional - validate format before writing ## write(fp, validate=True) ### Description Write an .cfg/.ini-format representation of the configuration state. ### Parameters #### Path Parameters - **fp** (TextIO) - Required - open file handle - **validate** (Boolean) - Optional - validate format before writing ## to_dict() ### Description Transform the configuration to a dictionary. ### Response - **dict** - dictionary with same content ``` -------------------------------- ### Create Development Environment Source: https://github.com/pyscaffold/configupdater/blob/main/docs/contributing.md Use this command to create a new Conda environment named 'configupdater' with necessary development tools like Python, virtualenv, and pytest. ```default conda create -n configupdater python=3 virtualenv pytest pytest-cov ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/pyscaffold/configupdater/blob/main/CONTRIBUTING.rst Commands to stage, commit, and push local changes to the remote repository. ```bash git add modified_files git commit ``` ```bash git push -u origin my-feature ``` -------------------------------- ### Handling Comments and Whitespace in ConfigUpdater Source: https://context7.com/pyscaffold/configupdater/llms.txt Add comments before options to provide context or explanations. This snippet shows how to use the `add_before.comment()` method to associate a comment with a specific configuration option. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject version = 1.0.0 """ updater = ConfigUpdater() updater.read_string(cfg) # Add a comment before an option ( updater["metadata"]["version"] .add_before.comment("Version follows semantic versioning") ) ``` -------------------------------- ### Configuration State After Renaming Summary Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md The configuration file state after renaming the 'summary' option to 'description'. ```ini [metadata] author = Ada Lovelace description = The Analytical Engine ``` -------------------------------- ### Add a section before an existing one Source: https://github.com/pyscaffold/configupdater/blob/main/README.md Demonstrates adding a new section with a comment and spacing before a target section. ```python updater = ConfigUpdater() updater.read_string(cfg) ( updater["metadata"] .add_before.section("options") .comment("Some specific project options") .space(2) ) ``` -------------------------------- ### Handle configuration exceptions and validation Source: https://context7.com/pyscaffold/configupdater/llms.txt Covers error handling for missing sections, duplicate entries, and parsing errors, along with safe existence checks. ```python from configupdater import ( ConfigUpdater, NoSectionError, NoOptionError, DuplicateSectionError, DuplicateOptionError, ParsingError, MissingSectionHeaderError ) cfg = """ [metadata] name = myproject """ updater = ConfigUpdater() updater.read_string(cfg) # Handle missing section try: value = updater["nonexistent"]["option"].value except KeyError as e: print(f"Section not found: {e}") # Output: Section not found: 'nonexistent' # Handle missing option with get fallback option = updater.get("metadata", "missing_option", fallback="default_value") print(f"Option value: {option}") # Output: Option value: default_value # Handle duplicate section try: updater.add_section("metadata") # Already exists except DuplicateSectionError as e: print(f"Duplicate section: {e}") # Output: Duplicate section: Section 'metadata' already exists # Handle parsing errors invalid_cfg = """ key_without_section = value [metadata] name = test """ try: bad_updater = ConfigUpdater() bad_updater.read_string(invalid_cfg) except MissingSectionHeaderError as e: print(f"Parsing error: Missing section header") # Output: Parsing error: Missing section header # Safe section and option checking if updater.has_section("metadata"): if updater.has_option("metadata", "name"): print(f"Name: {updater['metadata']['name'].value}") # Output: Name: myproject ``` -------------------------------- ### Add Option Before Another Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Add a new key-value pair before an existing key, including a comment. This demonstrates precise control over insertion points. ```python cfg = """ [metadata] author = Ada Lovelace summary = The Analytical Engine """ updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["summary"].add_before .comment("Ada would have loved MIT") .option("license", "MIT")) print(updater) ``` -------------------------------- ### Configuration Management Methods Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Methods for adding, removing, and retrieving sections and options within a configuration object. ```APIDOC ## remove_option(section, option) ### Description Remove a specific option from a section. ### Parameters #### Path Parameters - **section** (str) - Required - section name - **option** (str) - Required - option name ### Response - **bool** - whether the option was actually removed ## remove_section(name) ### Description Remove a file section. ### Parameters #### Path Parameters - **name** (str) - Required - name of the section ### Response - **bool** - whether the section was actually removed ## set(section, option, value) ### Description Set an option value. ### Parameters #### Path Parameters - **section** (str) - Required - section name - **option** (str) - Required - option name - **value** (None | str | Iterable[str]) - Optional - value, default None ``` -------------------------------- ### Add New Option to Configuration Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Add a new key-value pair to a section in the configuration. ```python updater["metadata"]["license"] = "MIT" ``` -------------------------------- ### Reading Configuration Files Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Functions for reading configuration data from files. ```APIDOC ## read(filename, encoding=None, into=None) ### Description Reads and parses a configuration file. ### Method Not applicable (function) ### Parameters #### Path Parameters - **filename** (str | bytes | PathLike) - Required - Path to the configuration file. - **encoding** (str | None) - Optional - Encoding of the file. Defaults to None. - **into** (Document) - Optional - An object to be populated with the parsed configuration. Defaults to None. ### Response #### Success Response (200) - **Document** - The parsed configuration document. ## read_file(f, source=None, into=None) ### Description Reads and parses configuration data from a file-like object. ### Method Not applicable (function) ### Parameters #### Path Parameters - **f** (Iterable[str]) - Required - A file-like object that yields strings (lines). - **source** (str | None) - Optional - The name of the source file. Defaults to None. - **into** (Document) - Optional - An object to be populated with the parsed configuration. Defaults to None. ### Response #### Success Response (200) - **Document** - The parsed configuration document. ``` -------------------------------- ### Reading Configuration from String Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Function for reading configuration data directly from a string. ```APIDOC ## read_string(string, source='', into=None) ### Description Reads and parses configuration data from a given string. ### Method Not applicable (function) ### Parameters #### Path Parameters - **string** (str) - Required - The string containing the configuration data. - **source** (str) - Optional - A reference name for the configuration source. Defaults to ''. - **into** (Document) - Optional - An object to be populated with the parsed configuration. Defaults to None. ### Response #### Success Response (200) - **Document** - The parsed configuration document. ``` -------------------------------- ### Add New Options Source: https://context7.com/pyscaffold/configupdater/llms.txt Add new options using dictionary assignment or the set method. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject author = Ada Lovelace """ updater = ConfigUpdater() updater.read_string(cfg) # Add a new option using dictionary-like syntax (appends to end of section) updater["metadata"]["license"] = "MIT" updater["metadata"]["version"] = "1.0.0" print(updater) # Using the set method at ConfigUpdater level updater.set("metadata", "description", "A sample project") print(updater["metadata"]["description"].value) ``` -------------------------------- ### Add Option with Comment Before Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Insert a new option with a preceding comment before a specific option. ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["summary"].add_before .comment("Ada would have loved MIT") .option("license", "MIT")) ``` -------------------------------- ### Configuring Custom Parser Options in ConfigUpdater Source: https://context7.com/pyscaffold/configupdater/llms.txt Customize how ConfigUpdater parses configuration files by specifying custom delimiters, comment prefixes, and handling of values without keys. This allows for flexibility with non-standard INI formats. ```python from configupdater import ConfigUpdater # Configuration with custom delimiters and comments custom_cfg = """ ; This is a comment with semicolon [database] host : localhost port : 5432 name : mydb """ # Custom parser options updater = ConfigUpdater( delimiters=(":", "="), # Accept both : and = as delimiters comment_prefixes=(";", "#"), # Accept both ; and # for comments allow_no_value=True, # Allow keys without values space_around_delimiters=True, # Add spaces around delimiters when writing empty_lines_in_values=True # Allow empty lines in multi-line values ) updater.read_string(custom_cfg) # Modify and print updater["database"]["port"].value = "5433" print(updater) # Output preserves original format: # ; This is a comment with semicolon # [database] # host : localhost # port : 5433 # name : mydb # Example with allow_no_value for flags flags_cfg = """ [features] debug verbose experimental """ updater2 = ConfigUpdater(allow_no_value=True) updater2.read_string(flags_cfg) # Check flag existence print(f"Debug enabled: {updater2.has_option('features', 'debug')}") # Output: Debug enabled: True ``` -------------------------------- ### ConfigUpdater Class Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md The main class for parsing and modifying configuration files. It supports loading content via read methods and manipulating the configuration like a nested dictionary. ```APIDOC ## Class: ConfigUpdater ### Description Tool to parse and modify existing cfg files. It follows the API of ConfigParser with specific differences regarding inline comments, single-file updates, and case preservation. ### Methods - **add_section(section)**: Create a new section in the configuration. Raises DuplicateSectionError if the section exists or ValueError if name is DEFAULT. - **clear()**: Remove all items from the configuration. - **get(section, option, fallback)**: Gets an option object for a given section or a fallback value. - **read() / read_file() / read_string()**: Methods to load configuration content. - **write() / update_file()**: Methods to save changes back to the file. ``` -------------------------------- ### Add Section Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Add a new section to the configuration. This operation is similar to adding options but at a higher level. ```python updater = ConfigUpdater() updater["options"] ``` -------------------------------- ### configupdater.Option Class Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Represents an option block holding a key/value pair within a configuration file. ```APIDOC ## class configupdater.Option ### Description Option block holding a key/value pair. ### Parameters - **key** (str) - Required - Key string associated with the option. - **value** (str | None) - Optional - Value associated with the given option. - **container** (Section | None) - Optional - Container holding the block. - **delimiter** (str) - Optional - Delimiter used, default '='. - **space_around_delimiters** (bool) - Optional - Whether to include spaces around delimiters. - **line** (str | None) - Optional - Raw line string. ### Methods - **append(value: str, **kwargs) -> Option**: Append a value to a multi-line value. - **as_list(separator='\n') -> list[str]**: Returns the value as a list. - **detach() -> B**: Remove and return this block from container. - **has_container() -> bool**: Checks if this block has a container attached. - **set_values(values: Iterable[str], separator='\n', indent: str | None = None, prepend_newline=True)**: Sets the value to a given list of options. ``` -------------------------------- ### Add New Option Source: https://github.com/pyscaffold/configupdater/blob/main/README.md Append a new key-value pair to an existing section. ```python updater = ConfigUpdater() updater.read_string(cfg) updater["metadata"]["license"] = "MIT" ``` -------------------------------- ### Add Section with Comment and Spacing Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Insert a new section with a comment and blank lines before an existing section. ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"].add_before .comment("Some specific project options") .section("options") .space(2)) ``` -------------------------------- ### Add Option with Comment After Source: https://github.com/pyscaffold/configupdater/blob/main/README.md Insert a new option after an existing one, including a comment. ```python updater = ConfigUpdater() updater.read_string(cfg) ( updater["metadata"]["author"] .add_after.comment("Ada would have loved MIT") .option("license", "MIT") ) ``` -------------------------------- ### Space Class Methods Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Details on methods and properties for the Space block. ```APIDOC ## Space Class Bases: `Block` **Description**: Represents vertical space block of new lines. ### *property* add_after *: BlockBuilder* **Description**: Block builder inserting a new block after the current block. ### *property* add_before *: BlockBuilder* **Description**: Block builder inserting a new block before the current block. ### add_line(line) **Description**: PRIVATE: Adds a line to the current block. This function is intended for internal use only. **Parameters**: - **line** (str) - One line to add. ### attach(container) **Description**: PRIVATE: Attaches the block to a container. Users should use add_* methods or bracket notation instead. **Parameters**: - **container** (Container) - The container to attach to. ### *property* container *: Container* **Description**: The container holding the block. ### *property* container_idx *: int* **Description**: The index of the block within its container. ### detach() **Description**: Removes and returns this block from its container. ### has_container() → bool **Description**: Checks if this block has a container attached. ### *property* next_block *: Block | None* **Description**: The next block in the current container. ### *property* previous_block *: Block | None* **Description**: The previous block in the current container. ### *property* updated *: bool* **Description**: True if the option was changed/updated, otherwise False. ``` -------------------------------- ### Resulting INI configuration Source: https://github.com/pyscaffold/configupdater/blob/main/README.md The resulting INI structure after adding the options section. ```ini [options] # Some specific project options [metadata] author = Ada Lovelace summary = The Analytical Engine ``` -------------------------------- ### Error Handling Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Details on exceptions raised by the ConfigUpdater library. ```APIDOC ### *exception* configupdater.ParsingError(source=None, filename=None) Bases: `Error` Raised when a configuration file does not follow legal syntax. #### add_note() Exception.add_note(note) – add a note to the exception #### with_traceback() Exception.with_traceback(tb) – set self._\_traceback_\_ to tb and return self. ``` -------------------------------- ### Access and Modify Options Source: https://context7.com/pyscaffold/configupdater/llms.txt Access sections and options using dictionary-like syntax and update values via the value property. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject version = 1.0.0 author = Ada Lovelace """ updater = ConfigUpdater() updater.read_string(cfg) # Access a section metadata_section = updater["metadata"] # Access an option's value current_author = updater["metadata"]["author"].value print(f"Current author: {current_author") # Output: Current author: Ada Lovelace # Modify an existing option value updater["metadata"]["version"].value = "2.0.0" updater["metadata"]["author"].value = "Alan Turing" print(updater) ``` -------------------------------- ### Section Class Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Represents a section within a configuration file. ```APIDOC ### *class* configupdater.Section(name: str, container: Document | None = None, raw_comment: str = '') Bases: `Block`, `Container`[[`Option`](#configupdater.Option) | [`Comment`](#configupdater.Comment) | [`Space`](#configupdater.Space)], `MutableMapping`[`str`, Option] Section block holding options #### *property* add_after *: BlockBuilder* Block builder inserting a new block after the current block #### *property* add_before *: BlockBuilder* Block builder inserting a new block before the current block #### add_comment(line: str) → S Add a Comment object to the section Used during initial parsing mainly * **Parameters:** **line** (*str*) – one line in the comment #### add_line(line: str) → B PRIVATE: this function is not part of the public API of Block. It is only used internally by other classes of the package during parsing. Add a line to the current block * **Parameters:** **line** (*str*) – one line to add #### add_option(entry: [Option](#configupdater.Option)) → S Add an Option object to the section Used during initial parsing mainly * **Parameters:** **entry** ([*Option*](#configupdater.Option)) – key value pair as Option object #### add_space(line: str) → S Add a Space object to the section Used during initial parsing mainly * **Parameters:** **line** (*str*) – one line that defines the space, maybe whitespaces #### attach(container: Container) → B PRIVATE: Don’t use this as a user! Rather use add_* or the bracket notation #### clear() → None. Remove all items from D. #### *property* container *: Container* Container holding the block #### *property* container_idx *: int* Index of the block within its container #### create_option(key: str, value: str | None = None) → [Option](#configupdater.Option) Creates an option with kwargs that respect syntax options given to the parent ConfigUpdater object (e.g. `space_around_delimiters`). #### WARNING This is a low level API, not intended for public use. Prefer [`set()`](#configupdater.Section.set) or `__setitem__()`. #### detach() → B Remove and return this block from container #### get(key: str) → [Option](#configupdater.Option) | None #### get(key: str, default: T) → [Option](#configupdater.Option) | T This method works similarly to `dict.get()`, and allows you to retrieve an option object by its key. #### has_container() → bool Checks if this block has a container attached #### has_option(key) → bool Returns whether the given option exists. * **Parameters:** **option** (*str*) – name of option * **Returns:** whether the section exists * **Return type:** bool #### insert_at(idx: int) → BlockBuilder Returns a builder inserting a new block at the given index * **Parameters:** **idx** (*int*) – index where to insert ``` -------------------------------- ### Add Option with Comment After Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Insert a new option with a preceding comment after a specific option. ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["author"].add_after .comment("Ada would have loved MIT") .option("license", "MIT")) ``` -------------------------------- ### Add Option After Another Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Add a new key-value pair after an existing key, including a comment. This shows an alternative method for precise insertion. ```python cfg = """ [metadata] author = Ada Lovelace summary = The Analytical Engine """ updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"]["author"].add_after .comment("Ada would have loved MIT") .option("license", "MIT")) print(updater) ``` -------------------------------- ### Add a new section before an existing one Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Inserts a new section with a comment and spacing before the specified metadata section. ```python updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"].add_before .section("options") .comment("Some specific project options") .space(2)) ``` -------------------------------- ### Retrieve an Option with a Default Value Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Use these patterns to obtain an Option object with a default value when the specified option is missing. ```python configupdater.get("section", "option", fallback=Option("name", value)) ``` ```python configupdater["section"].get("option", Option("name", value)) ``` -------------------------------- ### Rename Option Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Change the key name of an existing option. ```python updater = ConfigUpdater() updater.read_string(cfg) updater["metadata"]["summary"].key = "description" ``` -------------------------------- ### configupdater.Parser Class Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Parser for updating configuration files, following ConfigParser logic with specific modifications for preservation and control. ```APIDOC ## class configupdater.Parser ### Description Parser for updating configuration files. It keeps the original case of sections and keys and provides control over the position of new sections/keys. ### Parameters - **allow_no_value** (bool) - Optional - Whether to allow keys without values. - **delimiters** (Tuple[str, ...]) - Optional - Delimiters to use, default ('=', ':'). - **comment_prefixes** (Tuple[str, ...]) - Optional - Prefixes for comments, default ('#', ';'). - **inline_comment_prefixes** (Tuple[str, ...] | None) - Optional - Prefixes for inline comments. - **strict** (bool) - Optional - Whether to run in strict mode. - **empty_lines_in_values** (bool) - Optional - Whether to allow empty lines in values. - **space_around_delimiters** (bool) - Optional - Whether to include spaces around delimiters. - **optionxform** (Callable[[str], str]) - Optional - Function to transform option keys. ``` -------------------------------- ### Inject a section using detach Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Move a section from one ConfigUpdater instance to another using the detach method. ```default sphinx = ConfigUpdater() sphinx.read_string(sphinx_sect_str) sphinx_sect = sphinx["build_sphinx"] updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"].add_after .space() .section(sphinx_sect.detach())) ``` -------------------------------- ### Manage Git Branches Source: https://github.com/pyscaffold/configupdater/blob/main/CONTRIBUTING.rst Command to create a new feature branch for isolated development. ```bash git checkout -b my-feature ``` -------------------------------- ### Commit Changes Source: https://github.com/pyscaffold/configupdater/blob/main/docs/contributing.md Stage your modified files and commit them with a descriptive message. Replace 'modified_files' with the actual files you have changed. ```default git add modified_files git commit ``` -------------------------------- ### Remove Option Source: https://github.com/pyscaffold/configupdater/blob/main/README.rst Remove a key-value pair from the configuration. This is a straightforward way to delete specific settings. ```python cfg = """ [metadata] author = Ada Lovelace summary = The Analytical Engine """ updater = ConfigUpdater() updater.read_string(cfg) del updater["metadata"]["summary"] print(updater) ``` -------------------------------- ### Inject a section using detach Source: https://github.com/pyscaffold/configupdater/blob/main/README.md Moves a section from one ConfigUpdater object to another using the detach method. ```python sphinx = ConfigUpdater() sphinx.read_string(sphinx_sect_str) sphinx_sect = sphinx["build_sphinx"] updater = ConfigUpdater() updater.read_string(cfg) (updater["metadata"].add_after.space().section(sphinx_sect.detach())) ``` -------------------------------- ### Inject a section using deepcopy Source: https://github.com/pyscaffold/configupdater/blob/main/README.md Preserves the original section in the source object by using deepcopy instead of detach. ```python from copy import deepcopy (updater["metadata"].add_after.space().section(deepcopy(sphinx_sect))) ``` -------------------------------- ### Add New Section Programmatically Source: https://context7.com/pyscaffold/configupdater/llms.txt Create new sections and add them before or after existing sections, controlling comments and spacing. New sections can be added with associated comments and spacing. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject author = Ada Lovelace """ updater = ConfigUpdater() updater.read_string(cfg) # Add a section before metadata with comment and spacing (updater["metadata"] .add_before.comment("Build options for the project") .section("options") .space(1) ) # Add options to the new section updater["options"]["packages"] = "find:" updater["options"]["python_requires"] = ">=3.7" print(updater) ``` ```python # Add a section after metadata ( updater["metadata"] .add_after.space(1) .section("tool:pytest") ) updater["tool:pytest"]["testpaths"] = "tests" print(updater) ``` -------------------------------- ### Rename a configuration section Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Use the name attribute to rename an existing section within a ConfigUpdater object. ```default updater["metadata"].name = "MetaData" ``` -------------------------------- ### Rename and Remove Options Source: https://context7.com/pyscaffold/configupdater/llms.txt Rename options by modifying the key property and remove them using del or remove_option. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject summary = A short description author = Ada Lovelace deprecated_option = old_value """ updater = ConfigUpdater() updater.read_string(cfg) # Rename an option key updater["metadata"]["summary"].key = "description" # Remove an option using del del updater["metadata"]["deprecated_option"] print(updater) ``` -------------------------------- ### Push Changes to GitHub Source: https://github.com/pyscaffold/configupdater/blob/main/docs/contributing.md Push your committed changes to your fork on GitHub. This makes your branch available for creating a pull request. ```default git push -u origin my-feature ``` -------------------------------- ### Comment Class Source: https://github.com/pyscaffold/configupdater/blob/main/docs/api.md Represents a comment block within the configuration file, providing methods for navigation and modification. ```APIDOC ## Class: Comment ### Description Represents a comment block. Provides properties to navigate the block structure and methods to detach or update the block. ### Properties - **add_after**: BlockBuilder for inserting a new block after the current one. - **add_before**: BlockBuilder for inserting a new block before the current one. - **container**: The container holding the block. - **container_idx**: Index of the block within its container. - **next_block**: The next block in the container. - **previous_block**: The previous block in the container. - **updated**: Boolean indicating if the option was changed. ### Methods - **detach()**: Remove and return this block from the container. - **has_container()**: Checks if this block has a container attached. ``` -------------------------------- ### Rename and Remove Sections Source: https://context7.com/pyscaffold/configupdater/llms.txt Demonstrates renaming sections by modifying the `.name` property and removing sections using `del` or the `remove_section` method. `remove_section` returns True if the section was removed. ```python from configupdater import ConfigUpdater cfg = """ [metadata] name = myproject [old_section] key = value [options] packages = find: """ updater = ConfigUpdater() updater.read_string(cfg) # Rename a section updater["metadata"].name = "project.metadata" # Remove a section del updater["old_section"] print(updater) ``` ```python # Alternative: Use remove_section method updater2 = ConfigUpdater() updater2.read_string(cfg) removed = updater2.remove_section("old_section") print(f"Section removed: {removed}") ``` -------------------------------- ### Copy a section using deepcopy Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Preserve a section in the source object while adding a copy to the destination using deepcopy. ```default from copy import deepcopy (updater["metadata"].add_after .space() .section(deepcopy(sphinx_sect))) ``` -------------------------------- ### Update Existing Key Value Source: https://github.com/pyscaffold/configupdater/blob/main/docs/usage.md Modify the value of an existing key in the configuration. ```python updater["metadata"]["author"].value = "Alan Turing" ``` -------------------------------- ### Remove Option from Section Source: https://context7.com/pyscaffold/configupdater/llms.txt Demonstrates removing a specific option from a section using `remove_option`. Returns True if the option was removed, False otherwise. ```python updater2 = ConfigUpdater() updater2.read_string(cfg) removed = updater2.remove_option("metadata", "deprecated_option") print(f"Option removed: {removed}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.