confection


Nameconfection JSON
Version 0.1.5 PyPI version JSON
download
home_pagehttps://github.com/explosion/confection
SummaryThe sweetest config system for Python
upload_time2024-05-31 16:17:01
maintainerNone
docs_urlNone
authorExplosion
requires_python>=3.6
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <a href="https://explosion.ai"><img src="https://explosion.ai/assets/img/logo.svg" width="125" height="125" align="right" /></a>

# Confection: The sweetest config system for Python

`confection` :candy: is a lightweight library that offers a **configuration
system** letting you conveniently describe arbitrary trees of objects.

Configuration is a huge challenge for machine-learning code because you may want
to expose almost any detail of any function as a hyperparameter. The setting you
want to expose might be arbitrarily far down in your call stack, so it might
need to pass all the way through the CLI or REST API, through any number of
intermediate functions, affecting the interface of everything along the way. And
then once those settings are added, they become hard to remove later. Default
values also become hard to change without breaking backwards compatibility.

To solve this problem, `confection` offers a config system that lets you easily
describe arbitrary trees of objects. The objects can be created via function
calls you register using a simple decorator syntax. You can even version the
functions you create, allowing you to make improvements without breaking
backwards compatibility. The most similar config system we’re aware of is
[Gin](https://github.com/google/gin-config), which uses a similar syntax, and
also allows you to link the configuration system to functions in your code using
a decorator. `confection`'s config system is simpler and emphasizes a different
workflow via a subset of Gin’s functionality.

[![tests](https://github.com/explosion/confection/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/confection/actions/workflows/tests.yml)
[![Current Release Version](https://img.shields.io/github/v/release/explosion/confection.svg?style=flat-square&include_prereleases&logo=github)](https://github.com/explosion/confection/releases)
[![pypi Version](https://img.shields.io/pypi/v/confection.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.org/project/confection/)
[![conda Version](https://img.shields.io/conda/vn/conda-forge/confection.svg?style=flat-square&logo=conda-forge&logoColor=white)](https://anaconda.org/conda-forge/confection)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/ambv/black)

## ⏳ Installation

```bash
pip install confection
```

```bash
conda install -c conda-forge confection
```

## 👩‍💻 Usage

The configuration system parses a `.cfg` file like

```ini
[training]
patience = 10
dropout = 0.2
use_vectors = false

[training.logging]
level = "INFO"

[nlp]
# This uses the value of training.use_vectors
use_vectors = ${training.use_vectors}
lang = "en"
```

and resolves it to a `Dict`:

```json
{
  "training": {
    "patience": 10,
    "dropout": 0.2,
    "use_vectors": false,
    "logging": {
      "level": "INFO"
    }
  },
  "nlp": {
    "use_vectors": false,
    "lang": "en"
  }
}
```

The config is divided into sections, with the section name in square brackets –
for example, `[training]`. Within the sections, config values can be assigned to
keys using `=`. Values can also be referenced from other sections using the dot
notation and placeholders indicated by the dollar sign and curly braces. For
example, `${training.use_vectors}` will receive the value of use_vectors in the
training block. This is useful for settings that are shared across components.

The config format has three main differences from Python’s built-in
`configparser`:

1. JSON-formatted values. `confection` passes all values through `json.loads` to
   interpret them. You can use atomic values like strings, floats, integers or
   booleans, or you can use complex objects such as lists or maps.
2. Structured sections. `confection` uses a dot notation to build nested
   sections. If you have a section named `[section.subsection]`, `confection`
   will parse that into a nested structure, placing subsection within section.
3. References to registry functions. If a key starts with `@`, `confection` will
   interpret its value as the name of a function registry, load the function
   registered for that name and pass in the rest of the block as arguments. If
   type hints are available on the function, the argument values (and return
   value of the function) will be validated against them. This lets you express
   complex configurations, like a training pipeline where `batch_size` is
   populated by a function that yields floats.

There’s no pre-defined scheme you have to follow; how you set up the top-level
sections is up to you. At the end of it, you’ll receive a dictionary with the
values that you can use in your script – whether it’s complete initialized
functions, or just basic settings.

For instance, let’s say you want to define a new optimizer. You'd define its
arguments in `config.cfg` like so:

```ini
[optimizer]
@optimizers = "my_cool_optimizer.v1"
learn_rate = 0.001
gamma = 1e-8
```

To load and parse this configuration using a `catalogue` registry (install
[`catalogue`](https://github.com/explosion/catalogue) separately):

```python
import dataclasses
from typing import Union, Iterable
import catalogue
from confection import registry, Config

# Create a new registry.
registry.optimizers = catalogue.create("confection", "optimizers", entry_points=False)


# Define a dummy optimizer class.
@dataclasses.dataclass
class MyCoolOptimizer:
    learn_rate: float
    gamma: float


@registry.optimizers.register("my_cool_optimizer.v1")
def make_my_optimizer(learn_rate: Union[float, Iterable[float]], gamma: float):
    return MyCoolOptimizer(learn_rate, gamma)


# Load the config file from disk, resolve it and fetch the instantiated optimizer object.
config = Config().from_disk("./config.cfg")
resolved = registry.resolve(config)
optimizer = resolved["optimizer"]  # MyCoolOptimizer(learn_rate=0.001, gamma=1e-08)
```

> ⚠️ Caution: Type-checkers such as `mypy` will mark adding new attributes to `registry` this way - i. e. 
> `registry.new_attr = ...` - as errors. This is because a new attribute is added to the class after initialization. If 
> you are using typecheckers, you can either ignore this (e. g. with `# type: ignore` for `mypy`) or use a typesafe 
> alternative: instead of `registry.new_attr = ...`, use `setattr(registry, "new_attr", ...)`. 

Under the hood, `confection` will look up the `"my_cool_optimizer.v1"` function
in the "optimizers" registry and then call it with the arguments `learn_rate`
and `gamma`. If the function has type annotations, it will also validate the
input. For instance, if `learn_rate` is annotated as a float and the config
defines a string, `confection` will raise an error.

The Thinc documentation offers further information on the configuration system:

- [recursive blocks](https://thinc.ai/docs/usage-config#registry-recursive)
- [defining variable positional arguments](https://thinc.ai/docs/usage-config#registries-args)
- [using interpolation](https://thinc.ai/docs/usage-config#config-interpolation)
- [using custom registries](https://thinc.ai/docs/usage-config#registries-custom)
- [advanced type annotations with Pydantic](https://thinc.ai/docs/usage-config#advanced-types)
- [using base schemas](https://thinc.ai/docs/usage-config#advanced-types-base-schema)
- [filling a configuration with defaults](https://thinc.ai/docs/usage-config#advanced-types-fill-defaults)

## 🎛 API

### <kbd>class</kbd> `Config`

This class holds the model and training
[configuration](https://thinc.ai/docs/usage-config) and can load and save the
INI-style configuration format from/to a string, file or bytes. The `Config`
class is a subclass of `dict` and uses Python’s `ConfigParser` under the hood.

#### <sup><kbd>method</kbd> `Config.__init__`</sup>

Initialize a new `Config` object with optional data.

```python
from confection import Config
config = Config({"training": {"patience": 10, "dropout": 0.2}})
```

| Argument          | Type                                      | Description                                                                                                                                                 |
| ----------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data`            | `Optional[Union[Dict[str, Any], Config]]` | Optional data to initialize the config with.                                                                                                                |
| `section_order`   | `Optional[List[str]]`                     | Top-level section names, in order, used to sort the saved and loaded config. All other sections will be sorted alphabetically.                              |
| `is_interpolated` | `Optional[bool]`                          | Whether the config is interpolated or whether it contains variables. Read from the `data` if it’s an instance of `Config` and otherwise defaults to `True`. |

#### <sup><kbd>method</kbd> `Config.from_str`</sup>

Load the config from a string.

```python
from confection import Config

config_str = """
[training]
patience = 10
dropout = 0.2
"""
config = Config().from_str(config_str)
print(config["training"])  # {'patience': 10, 'dropout': 0.2}}
```

| Argument      | Type             | Description                                                                                                          |
| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `text`        | `str`            | The string config to load.                                                                                           |
| `interpolate` | `bool`           | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |
| `overrides`   | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
| **RETURNS**   | `Config`         | The loaded config.                                                                                                   |

#### <sup><kbd>method</kbd> `Config.to_str`</sup>

Load the config from a string.

```python
from confection import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
print(config.to_str()) # '[training]\npatience = 10\n\ndropout = 0.2'
```

| Argument      | Type   | Description                                                                 |
| ------------- | ------ | --------------------------------------------------------------------------- |
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
| **RETURNS**   | `str`  | The string config.                                                          |

#### <sup><kbd>method</kbd> `Config.to_bytes`</sup>

Serialize the config to a byte string.

```python
from confection import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config_bytes = config.to_bytes()
print(config_bytes)  # b'[training]\npatience = 10\n\ndropout = 0.2'
```

| Argument      | Type             | Description                                                                                                          |
| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `interpolate` | `bool`           | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |
| `overrides`   | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
| **RETURNS**   | `str`            | The serialized config.                                                                                               |

#### <sup><kbd>method</kbd> `Config.from_bytes`</sup>

Load the config from a byte string.

```python
from confection import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config_bytes = config.to_bytes()
new_config = Config().from_bytes(config_bytes)
```

| Argument      | Type     | Description                                                                 |
| ------------- | -------- | --------------------------------------------------------------------------- |
| `bytes_data`  | `bool`   | The data to load.                                                           |
| `interpolate` | `bool`   | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
| **RETURNS**   | `Config` | The loaded config.                                                          |

#### <sup><kbd>method</kbd> `Config.to_disk`</sup>

Serialize the config to a file.

```python
from confection import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config.to_disk("./config.cfg")
```

| Argument      | Type               | Description                                                                 |
| ------------- | ------------------ | --------------------------------------------------------------------------- |
| `path`        | `Union[Path, str]` | The file path.                                                              |
| `interpolate` | `bool`             | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |

#### <sup><kbd>method</kbd> `Config.from_disk`</sup>

Load the config from a file.

```python
from confection import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config.to_disk("./config.cfg")
new_config = Config().from_disk("./config.cfg")
```

| Argument      | Type               | Description                                                                                                          |
| ------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- |
| `path`        | `Union[Path, str]` | The file path.                                                                                                       |
| `interpolate` | `bool`             | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |
| `overrides`   | `Dict[str, Any]`   | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
| **RETURNS**   | `Config`           | The loaded config.                                                                                                   |

#### <sup><kbd>method</kbd> `Config.copy`</sup>

Deep-copy the config.

| Argument    | Type     | Description        |
| ----------- | -------- | ------------------ |
| **RETURNS** | `Config` | The copied config. |

#### <sup><kbd>method</kbd> `Config.interpolate`</sup>

Interpolate variables like `${section.value}` or `${section.subsection}` and
return a copy of the config with interpolated values. Can be used if a config is
loaded with `interpolate=False`, e.g. via `Config.from_str`.

```python
from confection import Config

config_str = """
[hyper_params]
dropout = 0.2

[training]
dropout = ${hyper_params.dropout}
"""
config = Config().from_str(config_str, interpolate=False)
print(config["training"])  # {'dropout': '${hyper_params.dropout}'}}
config = config.interpolate()
print(config["training"])  # {'dropout': 0.2}}
```

| Argument    | Type     | Description                                    |
| ----------- | -------- | ---------------------------------------------- |
| **RETURNS** | `Config` | A copy of the config with interpolated values. |

##### <sup><kbd>method</kbd> `Config.merge`</sup>

Deep-merge two config objects, using the current config as the default. Only
merges sections and dictionaries and not other values like lists. Values that
are provided in the updates are overwritten in the base config, and any new
values or sections are added. If a config value is a variable like
`${section.key}` (e.g. if the config was loaded with `interpolate=False)`, **the
variable is preferred**, even if the updates provide a different value. This
ensures that variable references aren’t destroyed by a merge.

> :warning: Note that blocks that refer to registered functions using the `@`
> syntax are only merged if they are referring to the same functions. Otherwise,
> merging could easily produce invalid configs, since different functions can
> take different arguments. If a block refers to a different function, it’s
> overwritten.

```python
from confection import Config

base_config_str = """
[training]
patience = 10
dropout = 0.2
"""
update_config_str = """
[training]
dropout = 0.1
max_epochs = 2000
"""

base_config = Config().from_str(base_config_str)
update_config = Config().from_str(update_config_str)
merged = Config(base_config).merge(update_config)
print(merged["training"])  # {'patience': 10, 'dropout': 0.1, 'max_epochs': 2000}
```

| Argument    | Type                            | Description                                         |
| ----------- | ------------------------------- | --------------------------------------------------- |
| `overrides` | `Union[Dict[str, Any], Config]` | The updates to merge into the config.               |
| **RETURNS** | `Config`                        | A new config instance containing the merged config. |

### Config Attributes

| Argument          | Type   | Description                                                                                                                                                              |
| ----------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `is_interpolated` | `bool` | Whether the config values have been interpolated. Defaults to `True` and is set to `False` if a config is loaded with `interpolate=False`, e.g. using `Config.from_str`. |

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/explosion/confection",
    "name": "confection",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": null,
    "author": "Explosion",
    "author_email": "contact@explosion.ai",
    "download_url": "https://files.pythonhosted.org/packages/51/d3/57c6631159a1b48d273b40865c315cf51f89df7a9d1101094ef12e3a37c2/confection-0.1.5.tar.gz",
    "platform": null,
    "description": "<a href=\"https://explosion.ai\"><img src=\"https://explosion.ai/assets/img/logo.svg\" width=\"125\" height=\"125\" align=\"right\" /></a>\n\n# Confection: The sweetest config system for Python\n\n`confection` :candy: is a lightweight library that offers a **configuration\nsystem** letting you conveniently describe arbitrary trees of objects.\n\nConfiguration is a huge challenge for machine-learning code because you may want\nto expose almost any detail of any function as a hyperparameter. The setting you\nwant to expose might be arbitrarily far down in your call stack, so it might\nneed to pass all the way through the CLI or REST API, through any number of\nintermediate functions, affecting the interface of everything along the way. And\nthen once those settings are added, they become hard to remove later. Default\nvalues also become hard to change without breaking backwards compatibility.\n\nTo solve this problem, `confection` offers a config system that lets you easily\ndescribe arbitrary trees of objects. The objects can be created via function\ncalls you register using a simple decorator syntax. You can even version the\nfunctions you create, allowing you to make improvements without breaking\nbackwards compatibility. The most similar config system we\u2019re aware of is\n[Gin](https://github.com/google/gin-config), which uses a similar syntax, and\nalso allows you to link the configuration system to functions in your code using\na decorator. `confection`'s config system is simpler and emphasizes a different\nworkflow via a subset of Gin\u2019s functionality.\n\n[![tests](https://github.com/explosion/confection/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/confection/actions/workflows/tests.yml)\n[![Current Release Version](https://img.shields.io/github/v/release/explosion/confection.svg?style=flat-square&include_prereleases&logo=github)](https://github.com/explosion/confection/releases)\n[![pypi Version](https://img.shields.io/pypi/v/confection.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.org/project/confection/)\n[![conda Version](https://img.shields.io/conda/vn/conda-forge/confection.svg?style=flat-square&logo=conda-forge&logoColor=white)](https://anaconda.org/conda-forge/confection)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/ambv/black)\n\n## \u23f3 Installation\n\n```bash\npip install confection\n```\n\n```bash\nconda install -c conda-forge confection\n```\n\n## \ud83d\udc69\u200d\ud83d\udcbb Usage\n\nThe configuration system parses a `.cfg` file like\n\n```ini\n[training]\npatience = 10\ndropout = 0.2\nuse_vectors = false\n\n[training.logging]\nlevel = \"INFO\"\n\n[nlp]\n# This uses the value of training.use_vectors\nuse_vectors = ${training.use_vectors}\nlang = \"en\"\n```\n\nand resolves it to a `Dict`:\n\n```json\n{\n  \"training\": {\n    \"patience\": 10,\n    \"dropout\": 0.2,\n    \"use_vectors\": false,\n    \"logging\": {\n      \"level\": \"INFO\"\n    }\n  },\n  \"nlp\": {\n    \"use_vectors\": false,\n    \"lang\": \"en\"\n  }\n}\n```\n\nThe config is divided into sections, with the section name in square brackets \u2013\nfor example, `[training]`. Within the sections, config values can be assigned to\nkeys using `=`. Values can also be referenced from other sections using the dot\nnotation and placeholders indicated by the dollar sign and curly braces. For\nexample, `${training.use_vectors}` will receive the value of use_vectors in the\ntraining block. This is useful for settings that are shared across components.\n\nThe config format has three main differences from Python\u2019s built-in\n`configparser`:\n\n1. JSON-formatted values. `confection` passes all values through `json.loads` to\n   interpret them. You can use atomic values like strings, floats, integers or\n   booleans, or you can use complex objects such as lists or maps.\n2. Structured sections. `confection` uses a dot notation to build nested\n   sections. If you have a section named `[section.subsection]`, `confection`\n   will parse that into a nested structure, placing subsection within section.\n3. References to registry functions. If a key starts with `@`, `confection` will\n   interpret its value as the name of a function registry, load the function\n   registered for that name and pass in the rest of the block as arguments. If\n   type hints are available on the function, the argument values (and return\n   value of the function) will be validated against them. This lets you express\n   complex configurations, like a training pipeline where `batch_size` is\n   populated by a function that yields floats.\n\nThere\u2019s no pre-defined scheme you have to follow; how you set up the top-level\nsections is up to you. At the end of it, you\u2019ll receive a dictionary with the\nvalues that you can use in your script \u2013 whether it\u2019s complete initialized\nfunctions, or just basic settings.\n\nFor instance, let\u2019s say you want to define a new optimizer. You'd define its\narguments in `config.cfg` like so:\n\n```ini\n[optimizer]\n@optimizers = \"my_cool_optimizer.v1\"\nlearn_rate = 0.001\ngamma = 1e-8\n```\n\nTo load and parse this configuration using a `catalogue` registry (install\n[`catalogue`](https://github.com/explosion/catalogue) separately):\n\n```python\nimport dataclasses\nfrom typing import Union, Iterable\nimport catalogue\nfrom confection import registry, Config\n\n# Create a new registry.\nregistry.optimizers = catalogue.create(\"confection\", \"optimizers\", entry_points=False)\n\n\n# Define a dummy optimizer class.\n@dataclasses.dataclass\nclass MyCoolOptimizer:\n    learn_rate: float\n    gamma: float\n\n\n@registry.optimizers.register(\"my_cool_optimizer.v1\")\ndef make_my_optimizer(learn_rate: Union[float, Iterable[float]], gamma: float):\n    return MyCoolOptimizer(learn_rate, gamma)\n\n\n# Load the config file from disk, resolve it and fetch the instantiated optimizer object.\nconfig = Config().from_disk(\"./config.cfg\")\nresolved = registry.resolve(config)\noptimizer = resolved[\"optimizer\"]  # MyCoolOptimizer(learn_rate=0.001, gamma=1e-08)\n```\n\n> \u26a0\ufe0f Caution: Type-checkers such as `mypy` will mark adding new attributes to `registry` this way - i. e. \n> `registry.new_attr = ...` - as errors. This is because a new attribute is added to the class after initialization. If \n> you are using typecheckers, you can either ignore this (e. g. with `# type: ignore` for `mypy`) or use a typesafe \n> alternative: instead of `registry.new_attr = ...`, use `setattr(registry, \"new_attr\", ...)`. \n\nUnder the hood, `confection` will look up the `\"my_cool_optimizer.v1\"` function\nin the \"optimizers\" registry and then call it with the arguments `learn_rate`\nand `gamma`. If the function has type annotations, it will also validate the\ninput. For instance, if `learn_rate` is annotated as a float and the config\ndefines a string, `confection` will raise an error.\n\nThe Thinc documentation offers further information on the configuration system:\n\n- [recursive blocks](https://thinc.ai/docs/usage-config#registry-recursive)\n- [defining variable positional arguments](https://thinc.ai/docs/usage-config#registries-args)\n- [using interpolation](https://thinc.ai/docs/usage-config#config-interpolation)\n- [using custom registries](https://thinc.ai/docs/usage-config#registries-custom)\n- [advanced type annotations with Pydantic](https://thinc.ai/docs/usage-config#advanced-types)\n- [using base schemas](https://thinc.ai/docs/usage-config#advanced-types-base-schema)\n- [filling a configuration with defaults](https://thinc.ai/docs/usage-config#advanced-types-fill-defaults)\n\n## \ud83c\udf9b API\n\n### <kbd>class</kbd> `Config`\n\nThis class holds the model and training\n[configuration](https://thinc.ai/docs/usage-config) and can load and save the\nINI-style configuration format from/to a string, file or bytes. The `Config`\nclass is a subclass of `dict` and uses Python\u2019s `ConfigParser` under the hood.\n\n#### <sup><kbd>method</kbd> `Config.__init__`</sup>\n\nInitialize a new `Config` object with optional data.\n\n```python\nfrom confection import Config\nconfig = Config({\"training\": {\"patience\": 10, \"dropout\": 0.2}})\n```\n\n| Argument          | Type                                      | Description                                                                                                                                                 |\n| ----------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `data`            | `Optional[Union[Dict[str, Any], Config]]` | Optional data to initialize the config with.                                                                                                                |\n| `section_order`   | `Optional[List[str]]`                     | Top-level section names, in order, used to sort the saved and loaded config. All other sections will be sorted alphabetically.                              |\n| `is_interpolated` | `Optional[bool]`                          | Whether the config is interpolated or whether it contains variables. Read from the `data` if it\u2019s an instance of `Config` and otherwise defaults to `True`. |\n\n#### <sup><kbd>method</kbd> `Config.from_str`</sup>\n\nLoad the config from a string.\n\n```python\nfrom confection import Config\n\nconfig_str = \"\"\"\n[training]\npatience = 10\ndropout = 0.2\n\"\"\"\nconfig = Config().from_str(config_str)\nprint(config[\"training\"])  # {'patience': 10, 'dropout': 0.2}}\n```\n\n| Argument      | Type             | Description                                                                                                          |\n| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |\n| `text`        | `str`            | The string config to load.                                                                                           |\n| `interpolate` | `bool`           | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |\n| `overrides`   | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `\"training.dropout\"` mapped to the value. |\n| **RETURNS**   | `Config`         | The loaded config.                                                                                                   |\n\n#### <sup><kbd>method</kbd> `Config.to_str`</sup>\n\nLoad the config from a string.\n\n```python\nfrom confection import Config\n\nconfig = Config({\"training\": {\"patience\": 10, \"dropout\": 0.2}})\nprint(config.to_str()) # '[training]\\npatience = 10\\n\\ndropout = 0.2'\n```\n\n| Argument      | Type   | Description                                                                 |\n| ------------- | ------ | --------------------------------------------------------------------------- |\n| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |\n| **RETURNS**   | `str`  | The string config.                                                          |\n\n#### <sup><kbd>method</kbd> `Config.to_bytes`</sup>\n\nSerialize the config to a byte string.\n\n```python\nfrom confection import Config\n\nconfig = Config({\"training\": {\"patience\": 10, \"dropout\": 0.2}})\nconfig_bytes = config.to_bytes()\nprint(config_bytes)  # b'[training]\\npatience = 10\\n\\ndropout = 0.2'\n```\n\n| Argument      | Type             | Description                                                                                                          |\n| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |\n| `interpolate` | `bool`           | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |\n| `overrides`   | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `\"training.dropout\"` mapped to the value. |\n| **RETURNS**   | `str`            | The serialized config.                                                                                               |\n\n#### <sup><kbd>method</kbd> `Config.from_bytes`</sup>\n\nLoad the config from a byte string.\n\n```python\nfrom confection import Config\n\nconfig = Config({\"training\": {\"patience\": 10, \"dropout\": 0.2}})\nconfig_bytes = config.to_bytes()\nnew_config = Config().from_bytes(config_bytes)\n```\n\n| Argument      | Type     | Description                                                                 |\n| ------------- | -------- | --------------------------------------------------------------------------- |\n| `bytes_data`  | `bool`   | The data to load.                                                           |\n| `interpolate` | `bool`   | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |\n| **RETURNS**   | `Config` | The loaded config.                                                          |\n\n#### <sup><kbd>method</kbd> `Config.to_disk`</sup>\n\nSerialize the config to a file.\n\n```python\nfrom confection import Config\n\nconfig = Config({\"training\": {\"patience\": 10, \"dropout\": 0.2}})\nconfig.to_disk(\"./config.cfg\")\n```\n\n| Argument      | Type               | Description                                                                 |\n| ------------- | ------------------ | --------------------------------------------------------------------------- |\n| `path`        | `Union[Path, str]` | The file path.                                                              |\n| `interpolate` | `bool`             | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |\n\n#### <sup><kbd>method</kbd> `Config.from_disk`</sup>\n\nLoad the config from a file.\n\n```python\nfrom confection import Config\n\nconfig = Config({\"training\": {\"patience\": 10, \"dropout\": 0.2}})\nconfig.to_disk(\"./config.cfg\")\nnew_config = Config().from_disk(\"./config.cfg\")\n```\n\n| Argument      | Type               | Description                                                                                                          |\n| ------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- |\n| `path`        | `Union[Path, str]` | The file path.                                                                                                       |\n| `interpolate` | `bool`             | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |\n| `overrides`   | `Dict[str, Any]`   | Overrides for values and sections. Keys are provided in dot notation, e.g. `\"training.dropout\"` mapped to the value. |\n| **RETURNS**   | `Config`           | The loaded config.                                                                                                   |\n\n#### <sup><kbd>method</kbd> `Config.copy`</sup>\n\nDeep-copy the config.\n\n| Argument    | Type     | Description        |\n| ----------- | -------- | ------------------ |\n| **RETURNS** | `Config` | The copied config. |\n\n#### <sup><kbd>method</kbd> `Config.interpolate`</sup>\n\nInterpolate variables like `${section.value}` or `${section.subsection}` and\nreturn a copy of the config with interpolated values. Can be used if a config is\nloaded with `interpolate=False`, e.g. via `Config.from_str`.\n\n```python\nfrom confection import Config\n\nconfig_str = \"\"\"\n[hyper_params]\ndropout = 0.2\n\n[training]\ndropout = ${hyper_params.dropout}\n\"\"\"\nconfig = Config().from_str(config_str, interpolate=False)\nprint(config[\"training\"])  # {'dropout': '${hyper_params.dropout}'}}\nconfig = config.interpolate()\nprint(config[\"training\"])  # {'dropout': 0.2}}\n```\n\n| Argument    | Type     | Description                                    |\n| ----------- | -------- | ---------------------------------------------- |\n| **RETURNS** | `Config` | A copy of the config with interpolated values. |\n\n##### <sup><kbd>method</kbd> `Config.merge`</sup>\n\nDeep-merge two config objects, using the current config as the default. Only\nmerges sections and dictionaries and not other values like lists. Values that\nare provided in the updates are overwritten in the base config, and any new\nvalues or sections are added. If a config value is a variable like\n`${section.key}` (e.g. if the config was loaded with `interpolate=False)`, **the\nvariable is preferred**, even if the updates provide a different value. This\nensures that variable references aren\u2019t destroyed by a merge.\n\n> :warning: Note that blocks that refer to registered functions using the `@`\n> syntax are only merged if they are referring to the same functions. Otherwise,\n> merging could easily produce invalid configs, since different functions can\n> take different arguments. If a block refers to a different function, it\u2019s\n> overwritten.\n\n```python\nfrom confection import Config\n\nbase_config_str = \"\"\"\n[training]\npatience = 10\ndropout = 0.2\n\"\"\"\nupdate_config_str = \"\"\"\n[training]\ndropout = 0.1\nmax_epochs = 2000\n\"\"\"\n\nbase_config = Config().from_str(base_config_str)\nupdate_config = Config().from_str(update_config_str)\nmerged = Config(base_config).merge(update_config)\nprint(merged[\"training\"])  # {'patience': 10, 'dropout': 0.1, 'max_epochs': 2000}\n```\n\n| Argument    | Type                            | Description                                         |\n| ----------- | ------------------------------- | --------------------------------------------------- |\n| `overrides` | `Union[Dict[str, Any], Config]` | The updates to merge into the config.               |\n| **RETURNS** | `Config`                        | A new config instance containing the merged config. |\n\n### Config Attributes\n\n| Argument          | Type   | Description                                                                                                                                                              |\n| ----------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `is_interpolated` | `bool` | Whether the config values have been interpolated. Defaults to `True` and is set to `False` if a config is loaded with `interpolate=False`, e.g. using `Config.from_str`. |\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "The sweetest config system for Python",
    "version": "0.1.5",
    "project_urls": {
        "Homepage": "https://github.com/explosion/confection"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0c003106b1854b45bd0474ced037dfe6b73b90fe68a68968cef47c23de3d43d2",
                "md5": "4477a8c0df3476f136775e020780dcef",
                "sha256": "e29d3c3f8eac06b3f77eb9dfb4bf2fc6bcc9622a98ca00a698e3d019c6430b14"
            },
            "downloads": -1,
            "filename": "confection-0.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4477a8c0df3476f136775e020780dcef",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 35451,
            "upload_time": "2024-05-31T16:16:59",
            "upload_time_iso_8601": "2024-05-31T16:16:59.075523Z",
            "url": "https://files.pythonhosted.org/packages/0c/00/3106b1854b45bd0474ced037dfe6b73b90fe68a68968cef47c23de3d43d2/confection-0.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "51d357c6631159a1b48d273b40865c315cf51f89df7a9d1101094ef12e3a37c2",
                "md5": "2e84d5944dfa5f1291f03c041c9781c3",
                "sha256": "8e72dd3ca6bd4f48913cd220f10b8275978e740411654b6e8ca6d7008c590f0e"
            },
            "downloads": -1,
            "filename": "confection-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "2e84d5944dfa5f1291f03c041c9781c3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 38924,
            "upload_time": "2024-05-31T16:17:01",
            "upload_time_iso_8601": "2024-05-31T16:17:01.559470Z",
            "url": "https://files.pythonhosted.org/packages/51/d3/57c6631159a1b48d273b40865c315cf51f89df7a9d1101094ef12e3a37c2/confection-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-31 16:17:01",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "explosion",
    "github_project": "confection",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "confection"
}
        
Elapsed time: 0.26302s