Skip to main content

Confuk

This is yet another package for managing configuration files in Python projects.

It exposes one function that lets you provide a path to a TOML/YAML/JSON configuration file. It parses the config file into a dictionary by default. If a config class is provided when parsing, the class instance will be created using a dictionary of keyword arguments coming from the original TOML/YAML/JSON file.

In human words: I made this package so that I don't have to explicilty load, parse and return a class instance every single time I have something to do with a configuration file:

from confuk import parse_config
from pathlib import Path
from somewhere import ConfigClass

cfg_dict = parse_config(Path("some.toml"))  # returns a dictionary
cfg_obj = parse_config(Path("some.toml"), ConfigClass)  # returns an instance of `ConfigClass`

Installation

pip install confuk

Or:

poetry add confuk

Building from source

You can build the package using Poetry:

  1. Clone this repo.
  2. Run poetry build.
  3. Grab the installable wheel from the dist folder and install it with pip or add the package as a local dependency of another project.

Special features

Config output formats

EasyDict

If you really hate referring to dictionary keys and you do not intend to create a custom configuration class for your config, you can parse the file to an EasyDict:

cfg_edict = parse_config(Path("some.toml"), "attr")

Now, if the key something exists in the configuration file, you can simply refer to it using an attribute:

cfg_edict.something

OmegaConf

OmegaConf is one of the most complete configuration systems for Python applications. If you want to leverage its features while still working with confuk as a front-end, you can simply parse the configuration into an instance of omegaconf.DictConfig by doing the following:

cfg = parse_config(Path("some.toml"), "omega")

Pydantic

If you're a fan of Pydantic with custom config classes for automatic validation, just use any class that inherits from BaseModel:

from confuk import parse_config
from pathlib import Path
from pydantic import BaseModel

class Metrics(BaseModel):
    psnr: float
    ssim: float


cfg_dict = parse_config(Path("some.toml"), Metrics)  # returns a dictionary

Supported input file formats

Currently we support the following input formats:

  • Declarative config formats:

    • .toml
    • .yaml
    • .json
  • Procedural config formats:

    • .py – a dictionary variable named config is required in the Python file to be loaded as a config instance.

Supported output formats

Format cfg_class argument
dict "d" / None
EasyDict "ed" / "edict" / "attr"
OmegaConf "o" / "omega" / "omegaconf"
pydantic BaseModel class
custom any class supporting **kwargs in the constructor

Imports

Because keeping hundreds of config files can become tedious, especially when there is shared values between them, you might want to consider using the imports functionality.

Say you have a TOML file from which you want to inherit values:

[something]
value = 1
another_value = 2

[something_else]
value = 3

You can "import" it using a preamble:

[pre]
imports = [
    "${this_dir}/test_imported.toml",
]

[something]
value = 69

This is equivalent to specifying a config like:

[something]
value = 69
another_value = 2

[something_else]
value = 3

Note that you can use several special interpolation markers to specify paths in the import section:

  • ${this_dir} -> points to a directory relative to the configuration file that contains the import section
  • ${cwd} -> points to the current working directory
  • ${this_filename} -> config filename (with extension)
  • ${this_filename_stem} -> filename without the extension (stem)
  • ${this_dirname} -> the name of the directory where the configuration file lives (not a path)
  • ${this_filename_suffix} -> suffix (without the dot) of the current configuration file

Lazy interpolation

By default the interpolation markers like ${this_filename} will interpolate the current file name. So if for example you create a.yaml and it contains:

pre:
  imports:
    - b.yaml

And b.yaml contains:

filename: "${this_filename}"

Then filename will be b.yaml. This is expected as these markers are interpolated as-is in the file they were found in.

So for example if you change b.yaml to contain:

filename: "$[this_filename]"

Then filename will be **a.yaml** if you have called parse_config on the a.yaml file.

What about inheriting selected values?

Unsupported. And I do not plan to add support for cherrypicking values from other configs. It makes things way messier in my opinion, as it becomes way harder to reason about the flow of variables.

As far as accessing other values within imported config, read the next section – that is supported via OmegaConf.

What about variable interpolation?

This is supported with the syntax that OmegaConf uses, e.g. path = "${some.root.path}/file.txt" will pick up the path variable from some.root config section. The interpolation markers that I mentioned in the Imports section should also work anywhere else within the config, so you can use your ${this_filename_stem} to refer to config names within the config itself. One use-case is when you want to have subdirectories in a results directory, where you would silo away the results from different configs:

results_dir = "results/${this_filename_stem}"

Assumming that you have 3 configs for your experiments: ex1, ex2 and ex3, you could instead put results_dir in a parent config to all those:

# to_import.toml:
results_dir = "results/${this_filename_stem}"

# ex1
[pre]
imports = ["${this_dir}/to_import.toml"]
a_variable_that_diverges_across_configs = 69

# ex2
[pre]
imports = ["${this_dir}/to_import.toml"]
a_variable_that_diverges_across_configs = 420

# ex3
[pre]
imports = ["${this_dir}/to_import.toml"]
a_variable_that_diverges_across_configs = 42

What about deeply nested configs?

If you like the deeply nested folder-file structure for your configs then Hydra might be more for you. I've used it before and it's very good but I personally find the design choice of creating directory structures for configs quite tedious.

confuk strives to be flatter: you import another config file in the preamble section and you have a choice of what to override. This makes it more comfortable to use when you have one default.toml config file for something and then create a bunch of configurations overriding certain values. This is useful for experiments in the AI/ML space, where I'm spending most of my time now.

You are of course free to structure your files as you please but don't expect a feature similar to Hydra's defaults in confuk – I do indeed use Hydra for applications which require such a system!

Lambda-configs (templates)

What if you want to reuse a portion of the config but parametrize on some variable? As an example imagine you want to have multiple variants in the config and want to reuse a YAML snippet in multiple places but with some variable changed:

experiment: "exp_1"

target_variants(crazy):
  - name: "Inactive target"
    id: "h1"
    configurations:
      - id: "HT"
        pdb: "data/${experiment}/s_${crazy}tg1.pdb"

variant_a: "${target_variants:awesome}"
variant_b: "${target_variants:amazing}"

In confuk you can simply specify a parameter (crazy in the example above). Underneath this will automatically create an OmegaConf resolver that accepts the right number of inputs. So if you want to "call" this pseudo-function with awesome you would use ${target_variants:awesome}.

Post-loading imports

Sometimes you might want to use an imported config which has some particular key interpolated from the file that actually imports it. For example assume test_post_imported.yaml looks like this:

some_key: "${deferred}"

Then you can use it like so:

deferred: "lol"

post:
  imports:
    - "${this_dir}/test_post_imported.yaml"

When loaded in the post section, the ${deferred} key will be interpolated in the imported config after the config which is the leaf node in the import graph. This way some_key will have the value of "lol" in the example.

Command-line overrides

One of the most fantastic features I've found when using Hydra was the ability to override values from the config file on the command line. This is convenient when you want to quickly test some changes to your configuration without going through the trouble of creating a new config file.

So I concluded it would be fun to implement it in confuk in a similar fashion. Here's how it works:

import confuk


@confuk.main(config=Path(__file__).parent / "test.toml", config_format="o", verbose=False)
def main(cfg, *args):
    console = Console()
    console.print(cfg)
    return cfg

This decorator behaves similarly to @hydra.main decorator and it creates a minimal argument parser for your application entrypoint under the hood.

Now, when running the app, you can specify any value overrides on the command line. For example if your config looks like this:

[my]
mother = 1

[your.dad]
father = 1

And you run your CLI app with the argument your.dad.father=3, you will override the pertinent value from 1 to 3.

Drop-in click argument parser overrides

We also have a drop-in decorator for click which adds a --config/-c option to your command line interface and any argument you feed via the CLI will simply override the top-level config keys:

@confuk.click_main("config.yaml", MyConfig)
@click.command()
@click.option('--lr', type=float, default=None)
def my_main(cfg, lr):
    # cfg loaded/overridden, lr passed through
    ...

If you want your CLI to override specific lower-level values in the config, you can leverage a drop-in click_option decorator with the cfg_path argument:

@confuk.click_main("config.yaml", MyConfig)
@click.command()
@confuk.click_option('--data', cfg_path="data.path")        # overrides cfg.data.path
@confuk.click_option('--lr', type=float, cfg_path="training.lr")  # overrides cfg.training.lr
@click.option('--epochs', type=int, default=None)           # overrides cfg.epochs (by name)
def my_main(cfg, data, lr, epochs):
    ...

Dumping configs

This is mostly for debugging purposes.

Sometimes, when you use a lot of imports it might be hard to figure out what is the final config form after all the imports have been resolved. Starting from version 0.8.0 you can now dump your configs to JSON, YAML, TOML, Pickle and JSONPickle and the routing is done using file extensions:

  • *.json – dump to JSON
  • *.yaml – dump to YAML
  • *.toml – dump to TOML
  • *.jsonp – dump to JSONPickle
  • *.pkl – dump to Pickle

To perform the dumping just use:

from confuk import dump_config

dump_config(cfg, "some_cfg.json")

Config file documentation

When designing a config file, you will often want to also document what each property means. Sadly enough, there aren't that many packages which handle config documentation very well. This is partially due to limitations of file formats used for configuration. For example YAML and TOML specifications do not cover parsing comments, meanwhile a lot of folks out there use comments to document parts of their config files:

apple:
  # Color of the apple
  color: red
  # Size of the apple
  size: medium

We thought of implementing parsing for these but seriously, who would have time to build a reliable new parser for YAML or TOML which also processes comments correctly? Instead, it was much simpler to go with a separate documentation file. For the example above, you would create another file, e.g. config.doc.yaml:

apple:
  _doc_: properties of an apple
  color:
    _doc_: Color of the apple
  size:
    _doc_: Size of the apple

Then you can simply run:

confuk doc ./config.doc.yaml

This will display the documentation in the console, paged for your pleasure of reading. You have currently the following alternative options to display the contents of the documentation:

  • confuk doc ./config.doc.yaml -f test.html – as an HTML file (append -o to open it in the web browser right away)
  • confuk doc ./config.doc.yaml -t – in a tree view (might be more helpful for figuring out complex hierarchies)

Parsing configs on the command line

Because sometimes you might want to display the cumulative config files after the imports and interpolations have been resolved, we added as an alternative to dumping to a file a command-line based print of the collected config:

confuk parse <path-to-config>

Logging

For more complex applications it's probably more useful to set up your own logging facilities the way you need them. For basic applications, you might use the get_console_and_logger function which accepts a simple logging config (which can be a part of your main config file):

logging:
  level: info
  logfile: null

The function returns a rich.console.Console and a logging.Logger instance which are tied together and can be used througout your application.

Populating dataclasses from OmegaConf configs

When you parse a config into an OmegaConf DictConfig and want to hydrate a typed dataclass from it, confuk provides from_config so you never have to hand-write a constructor full of OmegaConf.select(...) calls:

from dataclasses import dataclass
from confuk import parse_config, from_config

@dataclass
class TrainConfig:
    lr: float = 1e-3
    epochs: int = 100
    tag: str = "default"

raw = parse_config("train.toml", "omega")   # DictConfig
cfg = from_config(TrainConfig, raw)          # TrainConfig instance

The single rule: for every field of the dataclass, take the value from the config if it is present and not ??? (OmegaConf MISSING); otherwise leave it out of the constructor call so the dataclass's own default or default_factory applies. Required fields with no default that are absent from the config raise the normal TypeError from __init__.

You can also pass a plain dict directly — from_config wraps it in OmegaConf.create automatically.

Nested dataclasses

Type annotations are respected, so nested dataclass fields are populated recursively:

@dataclass
class Optimizer:
    name: str = "adam"
    lr: float = 1e-3

@dataclass
class TrainConfig:
    epochs: int = 100
    optimizer: Optimizer = field(default_factory=Optimizer)

A config section like [optimizer] (TOML) or an optimizer: key (YAML) will be recursively converted to an Optimizer instance. The same applies to list[SomeDataclass] and tuple[SomeDataclass, ...] fields — each element in the list is converted individually.

Keeping raw OmegaConf containers

If you declare a field with type DictConfig or ListConfig, from_config passes the value through unchanged so you retain the full OmegaConf API on that sub-tree:

from omegaconf import DictConfig
from dataclasses import dataclass

@dataclass
class Cfg:
    hyperparams: DictConfig   # stays as DictConfig, not converted

All other OmegaConf containers (e.g. a dict-like field typed as Any) are converted to native Python via OmegaConf.to_container(resolve=True), including resolving any remaining interpolations.

Strict mode

By default, extra keys in the config that have no corresponding dataclass field are silently ignored. Pass strict=True to raise a ValueError instead:

from_config(TrainConfig, raw, strict=True)
# ValueError: Unknown config keys for TrainConfig: ['typo_key']

ConfigMixin — classmethod on the dataclass itself

If you prefer calling MyConfig.from_config(cfg) rather than the standalone function, inherit from ConfigMixin:

from dataclasses import dataclass
from confuk import ConfigMixin

@dataclass
class TrainConfig(ConfigMixin):
    lr: float = 1e-3
    epochs: int = 100

cfg = TrainConfig.from_config(raw)
cfg = TrainConfig.from_config(raw, strict=True)

@config_dataclass — decorator without inheritance

If you would rather avoid adding a base class (for example to avoid MRO issues, or to decorate a dataclass defined elsewhere), use the config_dataclass decorator instead:

from dataclasses import dataclass
from confuk import config_dataclass

@config_dataclass
@dataclass
class TrainConfig:
    lr: float = 1e-3
    epochs: int = 100

cfg = TrainConfig.from_config(raw)

Both ConfigMixin and @config_dataclass are thin wrappers over the same from_config function and accept the same arguments.

Metadata

Release files for confuk 0.17.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for confuk 0.17.4
File Size Uploaded Provenance Actions
confuk-0.17.4.tar.gz 75.4 kB Without provenance Details for confuk-0.17.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for confuk 0.17.4
File Interpreter ABI Platform Actions
confuk-0.17.4-py3-none-any.whl Python 3 none any Details for confuk-0.17.4-py3-none-any.whl

Total release size: 105.1 kB

Release files / confuk-0.17.4.tar.gz

Download URL confuk-0.17.4.tar.gz
Size 75.4 kB
Tags Source
SHA-256 checksum
How to use checksums
541d23122cd8010aa1e3ac087e2555321119b426e533194f66e3414ae24def2a
BLAKE2b-256 checksum
How to use checksums
405c29e8ee8c720e41bb96bfa161b17347f314a364a3a15e5fff0da3ae897afc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / confuk-0.17.4-py3-none-any.whl

Download URL confuk-0.17.4-py3-none-any.whl
Size 29.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
23a09bdb287d76734902ace1cf53702a4b8d7d0321e445957231f667e92224fc
BLAKE2b-256 checksum
How to use checksums
a41c02049cb415b3c455f449c8679a5e6e02c6c1bd803dbcb0622d9c4c5562b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for confuk 0.17.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.17.4 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page