configparser-override


Nameconfigparser-override JSON
Version 0.8.0 PyPI version JSON
download
home_pageNone
SummaryConfigParser with environment variable and direct assignment overrides
upload_time2024-09-28 14:03:44
maintainerNone
docs_urlNone
authorRichard Nordström
requires_pythonNone
licenseNone
keywords cfg conf configparser configuration ini override parsing
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ConfigParser Override

[![Version](https://img.shields.io/pypi/v/configparser-override?color=blue)](https://pypi.org/project/configparser-override/)
[![Build
Status](https://github.com/RicNord/configparser-override/actions/workflows/ci.yaml/badge.svg)](https://github.com/RicNord/configparser-override/actions)

`ConfigParserOverride` enhances the pyhton standard library built-in
[ConfigParser](https://docs.python.org/3/library/configparser.html) by allowing
you to override or add new options using; environment variables and directly
assigned key-value arguments.

> **NOTE:** This package only depends on the Python Standard Library!

## Features

- Override configuration options with environment variables.
- Override configuration options with directly assigned arguments.
- Convert configuration object to a dataclass and cast the values to predefined
  datatypes.
- Find and collect configuration files in conventional locations based on your
  operating system.

## Install

```sh
pip install configparser-override
```

## Usage

Example of how to use `ConfigParserOverride`:

### Example `config.ini` File

```ini
[DEFAULT]
default_key1 = default_value1
default_key2 = default_value2

[section1]
key1 = value1
key2 = value2

[section2]
key3 = value3
key4 = value4
```

### Python Code

```python
import os

from configparser_override import ConfigParserOverride

# Optionally set environment variables for overriding
os.environ["MYAPP_DEFAULT_KEY1"] = "overridden_default_value1"
os.environ["MYAPP_SECTION1__KEY1"] = "overridden_value1"
os.environ["MYAPP_SECTION2__KEY3"] = "overridden_value3"

# Initialize the parser with an optional environment variable prefix and
# overrides from direct assignments.
parser = ConfigParserOverride(
    env_prefix="MYAPP_",
    # Sections & options are case insensitive by default
    SECTION2__KEY4="direct_override_value4",
    section2__key5="direct_override_value5",
)

# Read configuration from a file
parser.read(filenames="config.ini")

# Apply overrides
parser.apply_overrides()

# Access the configuration
print(config.defaults()["default_key1"])  # Output: overridden_default_value1
print(config.defaults()["default_key2"])  # Output: default_value2
print(config["section1"]["key1"])  # Output: overridden_value1
print(config["section1"]["key2"])  # Output: value2
print(config["section2"]["key3"])  # Output: overridden_value3
print(config["section2"]["key4"])  # Output: direct_override_value4
print(config["section2"]["key5"])  # Output: direct_override_value5
```

#### Configuration source precedence

Configuration options can be overridden in three ways. This is the order of
precedence:

1. **Directly assigned arguments** during initialization of the
   `ConfigParserOverride` class.
2. **Environment variables**.
3. **Configuration files**.

#### Environment variable configuration

To override configuration options, use environment variables with the following
format. Separate sections and options using double underscores (`__`):

- **With Prefix** (`MYAPP_` as an example):
  - For `DEFAULT` section: `[PREFIX][OPTION]`
  - For other sections: `[PREFIX][SECTION]__[OPTION]`

- **No Prefix**:
  - For `DEFAULT` section: `[OPTION]`
  - For other sections: `[SECTION]__[OPTION]`

**Example**:

- To override `key1` in `section1` with prefix `MYAPP_`, use
  `MYAPP_SECTION1__KEY1`.

## Find and collect configuration files

The library also contains a helper function `config_file_collector` that will
search for configuration files in conventional locations based on your OS.
The collected files can then be used as input to `ConfigParserOverride.read()`

### Searched paths

#### Linux and MacOS

Unix systems follows [XDG base directory
specification](https://specifications.freedesktop.org/basedir-spec/latest/) and
used environment variables:

- **XDG_CONFIG_HOME** (User config)
  - Default to **$HOME/.config**
- **XDG_CONFIG_DIRS** (System wide config)
  - List of directories separated by semicolon `:`
  - Default to **/etc/xdg**

#### Windows

Windows paths are specific in environment variables:

- **APPDATA** (User config)
  - Usually: **C:\Users\USERNAME\AppData\Roaming**
- **PROGRAMDATA** (System wide config)
  - Usually: **C:\ProgramData**

### Example

```python
from configparser_override import ConfigParserOverride, config_file_collector

collected_files = config_file_collector(file_name="config.ini", app_name="myapp")

print(collected_files)
# For Linux and MacOS
# Output: ["/etc/xdg/myapp/config.ini", "/home/USERNAME/.config/myapp/config.ini"]

# For Windows
# Output: ["C:/ProgramData/myapp/config.ini", "C:/Users/USERNAME/AppData/Roaming/myapp/config.ini"]

parser = ConfigParserOverride()
parser.read(filenames=collected_files)
parser.apply_overrides()
config = parser.config
```

## Convert to a Dataclass and Validate Data Types

The library features a `ConfigConverter` class, which enables the conversion of
configuration data into a dataclass instance. This functionality is
particularly useful for ensuring that the configuration adheres to the expected
format, since it tries to cast the option in the config to the types in the
dataclass. Hence, it also allows you to take advantage of various typing
frameworks and tools, such as integrations with your text editor, providing
enhanced validation and code assistance.

### Example

```python
from dataclasses import dataclass
from typing import Optional

from configparser_override import ConfigParserOverride


@dataclass
class Section1:
    key1: int
    key2: list[str]
    key3: Optional[str] = None


@dataclass
class ExampleConfig:
    section1: Section1


# Initialize the parser with overrides
parser = ConfigParserOverride(
    section1__key1="42", section1__key2="['item1', 'item2']"
)

# Read configuration from **optional** file
parser.read(filenames=[])

# Apply overrides
parser.apply_overrides()

# Convert to dataclass
config_as_dataclass = parser.to_dataclass(ExampleConfig)

print(config_as_dataclass.section1.key1)  # Output: 42
print(type(config_as_dataclass.section1.key1))  # Output: <class 'int'>
print(config_as_dataclass.section1.key2)  # Output: ['item1', 'item2']
print(type(config_as_dataclass.section1.key2))  # Output: <class 'list'>
print(config_as_dataclass.section1.key3)  # Output: None
```

### Data Types

Supported data types are:

- String
- Integer
- Bool
- Float
- Complex
- Bytes
- pathlib.Path

Collections (nesting is supported):

- List
- Dict
- Set
- Tuple

Others:

- None
- Optional | Option does not need to exist in config
- Union | Tries to cast until successful, in the order the types are specified
- Any | no type cast

## Platform Dependency

Different operating systems handle environment variables differently. Linux is
case sensitive while Windows is not. See [os.environ
docs](https://docs.python.org/3/library/os.html#os.environ). Hence, it is safest
to always use capitalized environment variables to avoid any unexpected
behavior.

### Recommendation

In order to avoid any unanticipated issues and make your code safe to run on
any platform, follow these rules:

| Element                       | Recommended Case |
|-------------------------------|------------------|
| Environment variables         | UPPERCASE        |
| Environment variable prefix   | UPPERCASE        |
| DEFAULT section in config.ini (as per convention in the standard library ConfigParser) | UPPERCASE |
| Sections in config.ini files  | lowercase        |
| Options in config.ini files   | lowercase        |
| Directly assigned arguments   | lowercase        |

### Case Sensitivity Handling

By default, `ConfigParserOverride` tries to stores everything as lowercase,
with the exception of `Section` headers that are read from configuration files,
where the existing casing in the file is honored. However, if you want to
override such a section with an environment variable or direct assignment, it
will recognize the existing casing of the section and continue to use that even
though you use other casing in the override method.

It is highly discouraged, but you can make `ConfigParserOverride` case-sensitive
by initializing it with the argument `case_sensitive_overrides=True`.

```python
from configparser_override import ConfigParserOverride

parser = ConfigParserOverride(env_prefix="MYAPP_", case_sensitive_overrides=True)
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "configparser-override",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "cfg, conf, configparser, configuration, ini, override, parsing",
    "author": "Richard Nordstr\u00f6m",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/2e/42/e4e82d23e9cb35469885ce4c5260101a8b167889b51d33d6e6303698f708/configparser_override-0.8.0.tar.gz",
    "platform": null,
    "description": "# ConfigParser Override\n\n[![Version](https://img.shields.io/pypi/v/configparser-override?color=blue)](https://pypi.org/project/configparser-override/)\n[![Build\nStatus](https://github.com/RicNord/configparser-override/actions/workflows/ci.yaml/badge.svg)](https://github.com/RicNord/configparser-override/actions)\n\n`ConfigParserOverride` enhances the pyhton standard library built-in\n[ConfigParser](https://docs.python.org/3/library/configparser.html) by allowing\nyou to override or add new options using; environment variables and directly\nassigned key-value arguments.\n\n> **NOTE:** This package only depends on the Python Standard Library!\n\n## Features\n\n- Override configuration options with environment variables.\n- Override configuration options with directly assigned arguments.\n- Convert configuration object to a dataclass and cast the values to predefined\n  datatypes.\n- Find and collect configuration files in conventional locations based on your\n  operating system.\n\n## Install\n\n```sh\npip install configparser-override\n```\n\n## Usage\n\nExample of how to use `ConfigParserOverride`:\n\n### Example `config.ini` File\n\n```ini\n[DEFAULT]\ndefault_key1 = default_value1\ndefault_key2 = default_value2\n\n[section1]\nkey1 = value1\nkey2 = value2\n\n[section2]\nkey3 = value3\nkey4 = value4\n```\n\n### Python Code\n\n```python\nimport os\n\nfrom configparser_override import ConfigParserOverride\n\n# Optionally set environment variables for overriding\nos.environ[\"MYAPP_DEFAULT_KEY1\"] = \"overridden_default_value1\"\nos.environ[\"MYAPP_SECTION1__KEY1\"] = \"overridden_value1\"\nos.environ[\"MYAPP_SECTION2__KEY3\"] = \"overridden_value3\"\n\n# Initialize the parser with an optional environment variable prefix and\n# overrides from direct assignments.\nparser = ConfigParserOverride(\n    env_prefix=\"MYAPP_\",\n    # Sections & options are case insensitive by default\n    SECTION2__KEY4=\"direct_override_value4\",\n    section2__key5=\"direct_override_value5\",\n)\n\n# Read configuration from a file\nparser.read(filenames=\"config.ini\")\n\n# Apply overrides\nparser.apply_overrides()\n\n# Access the configuration\nprint(config.defaults()[\"default_key1\"])  # Output: overridden_default_value1\nprint(config.defaults()[\"default_key2\"])  # Output: default_value2\nprint(config[\"section1\"][\"key1\"])  # Output: overridden_value1\nprint(config[\"section1\"][\"key2\"])  # Output: value2\nprint(config[\"section2\"][\"key3\"])  # Output: overridden_value3\nprint(config[\"section2\"][\"key4\"])  # Output: direct_override_value4\nprint(config[\"section2\"][\"key5\"])  # Output: direct_override_value5\n```\n\n#### Configuration source precedence\n\nConfiguration options can be overridden in three ways. This is the order of\nprecedence:\n\n1. **Directly assigned arguments** during initialization of the\n   `ConfigParserOverride` class.\n2. **Environment variables**.\n3. **Configuration files**.\n\n#### Environment variable configuration\n\nTo override configuration options, use environment variables with the following\nformat. Separate sections and options using double underscores (`__`):\n\n- **With Prefix** (`MYAPP_` as an example):\n  - For `DEFAULT` section: `[PREFIX][OPTION]`\n  - For other sections: `[PREFIX][SECTION]__[OPTION]`\n\n- **No Prefix**:\n  - For `DEFAULT` section: `[OPTION]`\n  - For other sections: `[SECTION]__[OPTION]`\n\n**Example**:\n\n- To override `key1` in `section1` with prefix `MYAPP_`, use\n  `MYAPP_SECTION1__KEY1`.\n\n## Find and collect configuration files\n\nThe library also contains a helper function `config_file_collector` that will\nsearch for configuration files in conventional locations based on your OS.\nThe collected files can then be used as input to `ConfigParserOverride.read()`\n\n### Searched paths\n\n#### Linux and MacOS\n\nUnix systems follows [XDG base directory\nspecification](https://specifications.freedesktop.org/basedir-spec/latest/) and\nused environment variables:\n\n- **XDG_CONFIG_HOME** (User config)\n  - Default to **$HOME/.config**\n- **XDG_CONFIG_DIRS** (System wide config)\n  - List of directories separated by semicolon `:`\n  - Default to **/etc/xdg**\n\n#### Windows\n\nWindows paths are specific in environment variables:\n\n- **APPDATA** (User config)\n  - Usually: **C:\\Users\\USERNAME\\AppData\\Roaming**\n- **PROGRAMDATA** (System wide config)\n  - Usually: **C:\\ProgramData**\n\n### Example\n\n```python\nfrom configparser_override import ConfigParserOverride, config_file_collector\n\ncollected_files = config_file_collector(file_name=\"config.ini\", app_name=\"myapp\")\n\nprint(collected_files)\n# For Linux and MacOS\n# Output: [\"/etc/xdg/myapp/config.ini\", \"/home/USERNAME/.config/myapp/config.ini\"]\n\n# For Windows\n# Output: [\"C:/ProgramData/myapp/config.ini\", \"C:/Users/USERNAME/AppData/Roaming/myapp/config.ini\"]\n\nparser = ConfigParserOverride()\nparser.read(filenames=collected_files)\nparser.apply_overrides()\nconfig = parser.config\n```\n\n## Convert to a Dataclass and Validate Data Types\n\nThe library features a `ConfigConverter` class, which enables the conversion of\nconfiguration data into a dataclass instance. This functionality is\nparticularly useful for ensuring that the configuration adheres to the expected\nformat, since it tries to cast the option in the config to the types in the\ndataclass. Hence, it also allows you to take advantage of various typing\nframeworks and tools, such as integrations with your text editor, providing\nenhanced validation and code assistance.\n\n### Example\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nfrom configparser_override import ConfigParserOverride\n\n\n@dataclass\nclass Section1:\n    key1: int\n    key2: list[str]\n    key3: Optional[str] = None\n\n\n@dataclass\nclass ExampleConfig:\n    section1: Section1\n\n\n# Initialize the parser with overrides\nparser = ConfigParserOverride(\n    section1__key1=\"42\", section1__key2=\"['item1', 'item2']\"\n)\n\n# Read configuration from **optional** file\nparser.read(filenames=[])\n\n# Apply overrides\nparser.apply_overrides()\n\n# Convert to dataclass\nconfig_as_dataclass = parser.to_dataclass(ExampleConfig)\n\nprint(config_as_dataclass.section1.key1)  # Output: 42\nprint(type(config_as_dataclass.section1.key1))  # Output: <class 'int'>\nprint(config_as_dataclass.section1.key2)  # Output: ['item1', 'item2']\nprint(type(config_as_dataclass.section1.key2))  # Output: <class 'list'>\nprint(config_as_dataclass.section1.key3)  # Output: None\n```\n\n### Data Types\n\nSupported data types are:\n\n- String\n- Integer\n- Bool\n- Float\n- Complex\n- Bytes\n- pathlib.Path\n\nCollections (nesting is supported):\n\n- List\n- Dict\n- Set\n- Tuple\n\nOthers:\n\n- None\n- Optional | Option does not need to exist in config\n- Union | Tries to cast until successful, in the order the types are specified\n- Any | no type cast\n\n## Platform Dependency\n\nDifferent operating systems handle environment variables differently. Linux is\ncase sensitive while Windows is not. See [os.environ\ndocs](https://docs.python.org/3/library/os.html#os.environ). Hence, it is safest\nto always use capitalized environment variables to avoid any unexpected\nbehavior.\n\n### Recommendation\n\nIn order to avoid any unanticipated issues and make your code safe to run on\nany platform, follow these rules:\n\n| Element                       | Recommended Case |\n|-------------------------------|------------------|\n| Environment variables         | UPPERCASE        |\n| Environment variable prefix   | UPPERCASE        |\n| DEFAULT section in config.ini (as per convention in the standard library ConfigParser) | UPPERCASE |\n| Sections in config.ini files  | lowercase        |\n| Options in config.ini files   | lowercase        |\n| Directly assigned arguments   | lowercase        |\n\n### Case Sensitivity Handling\n\nBy default, `ConfigParserOverride` tries to stores everything as lowercase,\nwith the exception of `Section` headers that are read from configuration files,\nwhere the existing casing in the file is honored. However, if you want to\noverride such a section with an environment variable or direct assignment, it\nwill recognize the existing casing of the section and continue to use that even\nthough you use other casing in the override method.\n\nIt is highly discouraged, but you can make `ConfigParserOverride` case-sensitive\nby initializing it with the argument `case_sensitive_overrides=True`.\n\n```python\nfrom configparser_override import ConfigParserOverride\n\nparser = ConfigParserOverride(env_prefix=\"MYAPP_\", case_sensitive_overrides=True)\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "ConfigParser with environment variable and direct assignment overrides",
    "version": "0.8.0",
    "project_urls": {
        "Issues": "https://github.com/RicNord/configparser-override/issues",
        "Repository": "https://github.com/RicNord/configparser-override.git"
    },
    "split_keywords": [
        "cfg",
        " conf",
        " configparser",
        " configuration",
        " ini",
        " override",
        " parsing"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "808f1022f0dd4d2eba89b1a66846d8e21911149b5a7590492de95321e66cfe50",
                "md5": "795ba8c495d3156eb769e213adaca44e",
                "sha256": "6c9c041b40962599651fb27c9adbb5e6f5adb8dc203e8eedb87862ae660d3acd"
            },
            "downloads": -1,
            "filename": "configparser_override-0.8.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "795ba8c495d3156eb769e213adaca44e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 16937,
            "upload_time": "2024-09-28T14:03:42",
            "upload_time_iso_8601": "2024-09-28T14:03:42.781552Z",
            "url": "https://files.pythonhosted.org/packages/80/8f/1022f0dd4d2eba89b1a66846d8e21911149b5a7590492de95321e66cfe50/configparser_override-0.8.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2e42e4e82d23e9cb35469885ce4c5260101a8b167889b51d33d6e6303698f708",
                "md5": "1f501215df5cd85088d6c3b29af91dfc",
                "sha256": "fedf157d8dedf3abef37a7427af1ae6f680f5b46a9f9570405b10a2a80116c4c"
            },
            "downloads": -1,
            "filename": "configparser_override-0.8.0.tar.gz",
            "has_sig": false,
            "md5_digest": "1f501215df5cd85088d6c3b29af91dfc",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 23670,
            "upload_time": "2024-09-28T14:03:44",
            "upload_time_iso_8601": "2024-09-28T14:03:44.500813Z",
            "url": "https://files.pythonhosted.org/packages/2e/42/e4e82d23e9cb35469885ce4c5260101a8b167889b51d33d6e6303698f708/configparser_override-0.8.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-28 14:03:44",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "RicNord",
    "github_project": "configparser-override",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "configparser-override"
}
        
Elapsed time: 4.40906s