Skip to main content

Toya

EN

A minimalistic library for flexible configuration reading.

Allows using the Jinja templating engine.

Values are evaluated lazily, after complete reading and merging of all configuration sources.

Project Integration

Module name: toya

Example integration with Rye:

rye add toya

Usage Example

test4.yaml:

c1: v1
c2: v2
c3:
  c31: v31
  c32: v32
  c33: !t "{{ _.c1 }}/{{ _.c2 }}/{{ c31 }}/{{ c32 }}"

Environment:

APP__C2=e2
APP__C3__C32=e32

Code:

from pathlib import Path
from typing import Any, MutableMapping

from toya.config import load_and_eval_config
from toya.supplier.env_supplier import EnvSupplier
from toya.supplier.mapping_supplier import MappingSupplier
from toya.supplier.yaml_supplier import YamlSupplier
from toya.tpl import create_tpl_type

yaml_supplier = YamlSupplier(Path("test4.yaml"))
env_supplier = EnvSupplier()

tpl_type = create_tpl_type()
mapping_supplier = MappingSupplier({
    "c3": {
        "c32": tpl_type("{{ _.c1 }}@{{ c31 }}")
    },
})

cfg: MutableMapping[str, Any] = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])

assert cfg["c3"]["c33"] == "v1/e2/v31/v1@v31"

Explanation

Configuration is read from the specified sources sequentially. A source specified later overwrites values from sources specified earlier.

Then the evaluation of values specified with the !t tag occurs (the tag can be specified during initialization). Values are evaluated sequentially, from top to bottom.

In templates, you can use all Jinja capabilities. Additionally, you can reference other variables.

  • If a variable name is specified without prefixes, it is considered to be a variable from the same group. For example, c33 references c31 without a prefix.
  • If you need to reference an arbitrary variable, you need to specify the full path to it, using the _ prefix as the root element. For example, c33 references c1 by specifying the full path _.c1. The variable c33 itself will have the full path _.c3.c33.

The result is returned as a dictionary. It can be used, for example, with Pydantic:

from pydantic import BaseModel

class Config(BaseModel):
    
    c1: str
    c2: str
  
    class C3(BaseModel):
          c33: str

    c3: C3
    
raw_cfg = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])
cfg = Config.model_validate(raw_cfg)

RU

Минималистичная библиотека для гибкого чтения конфигурации.

Позволяется использовать шаблонизатор Jinja.

Значения вычисляются отложено, после полного прочтения и слияния всех источников конфигурации.

Подключение в проект

Имя модуля: toya

Пример подключения в Rye:

rye add toya

Пример использования

test4.yaml:

c1: v1
c2: v2
c3:
  c31: v31
  c32: v32
  c33: !t "{{ _.c1 }}/{{ _.c2 }}/{{ c31 }}/{{ c32 }}"

Environment:

APP__C2=e2
APP__C3__C32=e32

Code:

from pathlib import Path
from typing import Any, MutableMapping

from toya.config import load_and_eval_config
from toya.supplier.env_supplier import EnvSupplier
from toya.supplier.mapping_supplier import MappingSupplier
from toya.supplier.yaml_supplier import YamlSupplier
from toya.tpl import create_tpl_type

yaml_supplier = YamlSupplier(Path("test4.yaml"))
env_supplier = EnvSupplier()

tpl_type = create_tpl_type()
mapping_supplier = MappingSupplier({
    "c3": {
        "c32": tpl_type("{{ _.c1 }}@{{ c31 }}")
    },
})

cfg: MutableMapping[str, Any] = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])

assert cfg["c3"]["c33"] == "v1/e2/v31/v1@v31"

Пояснение

Конфигурация читается из указанных источников последовательно. Источник, указанный позже, перезаписывает значения источников, указанных раньше.

Далее происходит вычисление значений, указанных с тегом !t (тег можно указать при инициализации). Значения вычисляются последовательно, сверху вниз.

В шаблонах можно использовать все возможности Jinja. Кроме того можно ссылаться на другие переменные.

  • Если имя переменной указано без префиксов, то считается, что это переменная из той же группы. Например, c33 обращается к с31 без префикса.
  • Если нужно обратиться к произвольной переменной, то нужно указать полный путь к ней, используя префикс _ как корневой элемент. Например, c33 обращается к c1 с указанием полного пути _.c1. Сама переменная с33 будет иметь полный путь _.c3.c33.

Результат возвращается в виде словаря. Его можно использовать, например, с Pydantic:

from pydantic import BaseModel

class Config(BaseModel):
    
    c1: str
    c2: str
  
    class C3(BaseModel):
          c33: str

    c3: C3
    
raw_cfg = load_and_eval_config([yaml_supplier, env_supplier, mapping_supplier])
cfg = Config.model_validate(raw_cfg)

Metadata

Release files for toya 1.0.3

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

Source distribution (sdist)

Source distribution for toya 1.0.3
File Size Uploaded
toya-1.0.3.tar.gz 8.7 kB Details

Built distribution (wheel)

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

Total release size: 15.8 kB

Release files / toya-1.0.3.tar.gz

Download URL toya-1.0.3.tar.gz
Size 8.7 kB
Tags Source
SHA-256 checksum
How to use checksums
67a616c4097b50f7b910d0a80bc53223799952d4440920a0ad618482f9b3a5ed
BLAKE2b-256 checksum
How to use checksums
dea0b7f70aae46056ac4b0af5fcc1b0289646334ca2aa6f5021254f7cf18e72f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 23, 2025.

Transparency log

Release files / toya-1.0.3-py3-none-any.whl

Download URL toya-1.0.3-py3-none-any.whl
Size 7.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6ee1a305d58704f37288726038c0c23beb529b20d06ec1b5bade332e63ef4a4e
BLAKE2b-256 checksum
How to use checksums
dfd1a251be4ae37f3f68a1d502da214a7691a077872cceb5e3ad0a5adaf4ecc9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jun 23, 2025.

Transparency log

Release history Release notifications | RSS feed

This release

1.0.3 This release

2 release files

1.0.2

2 release files

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