tidyconf 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tidyconf/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """tidyconf: small, layered configuration for small apps."""
2
+
3
+ from tidyconf.config import Config, optional
4
+ from tidyconf.exceptions import ConfigError, KeyNotFoundError
5
+
6
+ __version__ = "1.0.0"
7
+
8
+ __all__ = ["Config", "ConfigError", "KeyNotFoundError", "optional"]
tidyconf/config.py ADDED
@@ -0,0 +1,205 @@
1
+ """The Config class plus file merging and environment overrides."""
2
+
3
+ import copy
4
+ import json
5
+ import os
6
+ from collections.abc import Mapping, MutableMapping
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any, Self
10
+
11
+ from tidyconf.exceptions import ConfigError, KeyNotFoundError
12
+ from tidyconf.loaders import _load_file
13
+
14
+ _MISSING: Any = object()
15
+ _TRUE = {"true", "1", "yes", "on"}
16
+ _FALSE = {"false", "0", "no", "off"}
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class OptionalFile:
21
+ """A config file that is skipped if it does not exist."""
22
+
23
+ path: Path
24
+
25
+
26
+ def optional(path: str | os.PathLike[str]) -> OptionalFile:
27
+ """Mark a config file as optional for `Config.load`.
28
+
29
+ Args:
30
+ path: Path to the config file.
31
+
32
+ Returns:
33
+ A marker that `Config.load` skips if the file is missing.
34
+ """
35
+ return OptionalFile(Path(path))
36
+
37
+
38
+ class Config:
39
+ """Nested configuration values addressed by dotted routes like "db.port"."""
40
+
41
+ def __init__(self, data: Mapping[str, Any] | None = None) -> None:
42
+ """Create a config from a mapping, which is deep-copied.
43
+
44
+ Args:
45
+ data: Initial values. `reset()` returns to this state.
46
+ """
47
+ self._initial: dict[str, Any] = copy.deepcopy(dict(data or {}))
48
+ self._data: dict[str, Any] = copy.deepcopy(self._initial)
49
+
50
+ @classmethod
51
+ def load(
52
+ cls,
53
+ *sources: str | os.PathLike[str] | OptionalFile,
54
+ env_prefix: str | None = None,
55
+ ) -> Self:
56
+ """Load and deep-merge config files, then apply environment overrides.
57
+
58
+ Args:
59
+ *sources: JSON, TOML or YAML files; later files override earlier ones.
60
+ Wrap a path in `optional()` to skip it if it does not exist.
61
+ env_prefix: If given, variables named `<PREFIX>_SECTION__KEY` override
62
+ the value at route `section.key`, which must exist in the files.
63
+
64
+ Returns:
65
+ The loaded config. `reset()` returns to this state.
66
+
67
+ Raises:
68
+ FileNotFoundError: A required file does not exist.
69
+ ConfigError: A file or environment variable could not be used.
70
+ """
71
+ data: dict[str, Any] = {}
72
+ for source in sources:
73
+ path = source.path if isinstance(source, OptionalFile) else source
74
+ try:
75
+ loaded = _load_file(path)
76
+ except FileNotFoundError:
77
+ if isinstance(source, OptionalFile):
78
+ continue
79
+ raise
80
+ data = _deep_merge(data, loaded)
81
+ if env_prefix is not None:
82
+ _apply_env(data, env_prefix)
83
+ return cls(data)
84
+
85
+ def get(self, route: str, default: Any = _MISSING) -> Any:
86
+ """Return a deep copy of the value at a dotted route.
87
+
88
+ Args:
89
+ route: Dotted route such as "database.port".
90
+ default: Returned instead of raising if the route does not exist.
91
+
92
+ Raises:
93
+ KeyNotFoundError: The route does not exist and no default was given.
94
+ """
95
+ value = self._lookup(route)
96
+ if value is _MISSING:
97
+ if default is _MISSING:
98
+ raise KeyNotFoundError(f"Key '{route}' not found")
99
+ return default
100
+ return copy.deepcopy(value)
101
+
102
+ def __getitem__(self, route: str) -> Any:
103
+ return self.get(route)
104
+
105
+ def __contains__(self, route: object) -> bool:
106
+ """Return whether a dotted route exists, e.g. `"database.port" in config`."""
107
+ return isinstance(route, str) and self._lookup(route) is not _MISSING
108
+
109
+ def _lookup(self, route: str) -> Any:
110
+ node: Any = self._data
111
+ for key in route.split("."):
112
+ if not isinstance(node, Mapping) or key not in node:
113
+ return _MISSING
114
+ node = node[key]
115
+ return node
116
+
117
+ def set(self, route: str, value: Any) -> None:
118
+ """Set the value at a dotted route, creating intermediate sections.
119
+
120
+ Raises:
121
+ TypeError: An intermediate value exists but is not a mapping.
122
+ """
123
+ *parents, last = route.split(".")
124
+ node: MutableMapping[str, Any] = self._data
125
+ for i, key in enumerate(parents):
126
+ child = node.setdefault(key, {})
127
+ if not isinstance(child, MutableMapping):
128
+ prefix = ".".join(parents[: i + 1])
129
+ raise TypeError(f"Cannot set '{route}': '{prefix}' is not a mapping")
130
+ node = child
131
+ node[last] = value
132
+
133
+ def reset(self) -> None:
134
+ """Restore the state from construction or `load()`."""
135
+ self._data = copy.deepcopy(self._initial)
136
+
137
+ def to_dict(self) -> dict[str, Any]:
138
+ """Return a deep copy of all values."""
139
+ return copy.deepcopy(self._data)
140
+
141
+ def __repr__(self) -> str:
142
+ return f"Config({self._data!r})"
143
+
144
+
145
+ def _deep_merge(base: Mapping[str, Any], override: Mapping[str, Any]) -> dict[str, Any]:
146
+ result = dict(base)
147
+ for key, value in override.items():
148
+ if isinstance(result.get(key), Mapping) and isinstance(value, Mapping):
149
+ result[key] = _deep_merge(result[key], value)
150
+ else:
151
+ result[key] = value
152
+ return result
153
+
154
+
155
+ def _apply_env(data: dict[str, Any], prefix: str) -> None:
156
+ start = f"{prefix}_".lower()
157
+ for name in sorted(os.environ):
158
+ if not name.lower().startswith(start):
159
+ continue
160
+ segments = name[len(start) :].lower().split("__")
161
+ node = data
162
+ for i, segment in enumerate(segments):
163
+ if not isinstance(node, dict):
164
+ raise ConfigError(f"{name}: '{segments[i - 1]}' is not a mapping")
165
+ key = _match_key(node, segment)
166
+ if key is None:
167
+ route = ".".join(segments[: i + 1])
168
+ raise ConfigError(
169
+ f"{name}: '{route}' is not defined in the config files"
170
+ )
171
+ if i == len(segments) - 1:
172
+ node[key] = _convert(name, os.environ[name], node[key])
173
+ else:
174
+ node = node[key]
175
+
176
+
177
+ def _match_key(node: Mapping[str, Any], segment: str) -> str | None:
178
+ return next((k for k in node if isinstance(k, str) and k.lower() == segment), None)
179
+
180
+
181
+ def _convert(name: str, raw: str, current: Any) -> Any:
182
+ if isinstance(current, bool):
183
+ if raw.lower() in _TRUE:
184
+ return True
185
+ if raw.lower() in _FALSE:
186
+ return False
187
+ raise ConfigError(f"{name}: expected a boolean, got {raw!r}")
188
+ if isinstance(current, int | float):
189
+ target = int if isinstance(current, int) else float
190
+ try:
191
+ return target(raw)
192
+ except ValueError as err:
193
+ message = f"{name}: expected {target.__name__}, got {raw!r}"
194
+ raise ConfigError(message) from err
195
+ if isinstance(current, list):
196
+ try:
197
+ value = json.loads(raw)
198
+ except json.JSONDecodeError as err:
199
+ raise ConfigError(f"{name}: expected a JSON list, got {raw!r}") from err
200
+ if not isinstance(value, list):
201
+ raise ConfigError(f"{name}: expected a JSON list, got {raw!r}")
202
+ return value
203
+ if isinstance(current, Mapping):
204
+ raise ConfigError(f"{name}: cannot override a whole section")
205
+ return raw
tidyconf/exceptions.py ADDED
@@ -0,0 +1,13 @@
1
+ """Exceptions raised by tidyconf."""
2
+
3
+
4
+ class ConfigError(Exception):
5
+ """Raised for unreadable files, unsupported formats and bad env values."""
6
+
7
+
8
+ class KeyNotFoundError(ConfigError, KeyError):
9
+ """Raised when a route does not exist in the configuration."""
10
+
11
+ def __str__(self) -> str:
12
+ # KeyError.__str__ would wrap the message in quotes.
13
+ return str(self.args[0]) if self.args else ""
tidyconf/loaders.py ADDED
@@ -0,0 +1,51 @@
1
+ """Reading config files, with the format chosen by file suffix."""
2
+
3
+ import json
4
+ import os
5
+ import tomllib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from tidyconf.exceptions import ConfigError
10
+
11
+
12
+ def _load_file(path: str | os.PathLike[str]) -> dict[str, Any]:
13
+ path = Path(path)
14
+ suffix = path.suffix.lower()
15
+ if suffix not in (".json", ".toml", ".yaml", ".yml"):
16
+ raise ConfigError(f"Unsupported config file type: '{path.suffix}' ({path})")
17
+
18
+ try:
19
+ if suffix == ".json":
20
+ with path.open(encoding="utf-8") as file:
21
+ data = json.load(file)
22
+ elif suffix == ".toml":
23
+ with path.open("rb") as file:
24
+ data = tomllib.load(file)
25
+ else:
26
+ data = _load_yaml(path)
27
+ except (json.JSONDecodeError, tomllib.TOMLDecodeError, UnicodeDecodeError) as err:
28
+ raise ConfigError(f"Could not parse {path}: {err}") from err
29
+
30
+ if not isinstance(data, dict):
31
+ raise ConfigError(
32
+ f"{path}: top level must be a mapping, got {type(data).__name__}"
33
+ )
34
+ return data
35
+
36
+
37
+ def _load_yaml(path: Path) -> Any:
38
+ # Read first, so a missing optional file is skipped even without PyYAML.
39
+ text = path.read_text(encoding="utf-8")
40
+ try:
41
+ import yaml
42
+ except ImportError:
43
+ raise ConfigError(
44
+ "Reading YAML files requires PyYAML: pip install tidyconf[yaml]"
45
+ ) from None
46
+
47
+ try:
48
+ data = yaml.safe_load(text)
49
+ except yaml.YAMLError as err:
50
+ raise ConfigError(f"Could not parse {path}: {err}") from err
51
+ return {} if data is None else data
tidyconf/py.typed ADDED
File without changes
@@ -0,0 +1,220 @@
1
+ Metadata-Version: 2.5
2
+ Name: tidyconf
3
+ Version: 1.0.0
4
+ Summary: Simple, typed configuration for small apps: JSON/TOML/YAML files, layering and env overrides.
5
+ Project-URL: Homepage, https://github.com/pgoelter/tidyconf
6
+ Project-URL: Source, https://github.com/pgoelter/tidyconf
7
+ Project-URL: Issues, https://github.com/pgoelter/tidyconf/issues
8
+ Author: Philipp Gölter
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: config,configuration,env,json,settings,toml,yaml
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Provides-Extra: yaml
22
+ Requires-Dist: pyyaml>=6; extra == 'yaml'
23
+ Description-Content-Type: text/markdown
24
+
25
+ [![CI](https://github.com/pgoelter/tidyconf/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/pgoelter/tidyconf/actions/workflows/main.yml)
26
+
27
+ # tidyconf
28
+
29
+ Simple configuration for small, self-hosted apps. Load settings from JSON, TOML or
30
+ YAML files, layer a local override file on top of the defaults, let environment
31
+ variables override single values, and read everything through dotted routes like
32
+ `config["database.port"]`. Fully typed, Python 3.11+, no dependencies (PyYAML only
33
+ if you use YAML files).
34
+
35
+ ## Install
36
+
37
+ ```sh
38
+ pip install tidyconf # JSON and TOML
39
+ pip install "tidyconf[yaml]" # plus YAML support (PyYAML)
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ `config.toml` (defaults, committed to the repo):
45
+
46
+ ```toml
47
+ debug = false
48
+
49
+ [server]
50
+ host = "127.0.0.1"
51
+ port = 8000
52
+
53
+ [database]
54
+ url = "sqlite:///app.db"
55
+ pool_size = 5
56
+
57
+ [features]
58
+ enabled = ["search"]
59
+ ```
60
+
61
+ `config.local.yml` (optional, per machine, not committed):
62
+
63
+ ```yaml
64
+ server:
65
+ host: 0.0.0.0
66
+ database:
67
+ url: postgresql://localhost/myapp
68
+ ```
69
+
70
+ Environment (e.g. set by Docker or systemd):
71
+
72
+ ```sh
73
+ export MYAPP_SERVER__PORT=9000
74
+ export MYAPP_DEBUG=true
75
+ ```
76
+
77
+ Load and read:
78
+
79
+ ```python
80
+ from tidyconf import Config, optional
81
+
82
+ config = Config.load(
83
+ "config.toml",
84
+ optional("config.local.yml"), # skipped if the file does not exist
85
+ env_prefix="MYAPP",
86
+ )
87
+
88
+ config["server.host"] # '0.0.0.0' (from config.local.yml)
89
+ config["server.port"] # 9000 (from env, converted to int)
90
+ config.get("debug") # True (from env, converted to bool)
91
+ config.get("database") # {'url': 'postgresql://localhost/myapp', 'pool_size': 5}
92
+ config.get("cache.ttl", default=60) # 60 (missing key, default used)
93
+ config["cache.ttl"] # raises KeyNotFoundError
94
+ ```
95
+
96
+ ### Sharing one config across your app
97
+
98
+ There is no global singleton. Load the config once in a module and import it
99
+ wherever you need it; Python's module cache makes it a single shared object:
100
+
101
+ ```python
102
+ # myapp/settings.py
103
+ from pathlib import Path
104
+
105
+ from tidyconf import Config, optional
106
+
107
+ BASE_DIR = Path(__file__).resolve().parent
108
+
109
+ config = Config.load(
110
+ BASE_DIR / "config.toml",
111
+ optional(BASE_DIR / "config.local.yml"),
112
+ env_prefix="MYAPP",
113
+ )
114
+ ```
115
+
116
+ ```python
117
+ # myapp/server.py
118
+ from myapp.settings import config
119
+
120
+
121
+ def run() -> None:
122
+ serve(host=config["server.host"], port=config["server.port"])
123
+ ```
124
+
125
+ Relative paths are resolved against the current working directory, so building
126
+ them from `__file__` as above keeps loading independent of where the app is started.
127
+
128
+ A runnable version of this setup, a tiny web server, lives in
129
+ [`examples/app.py`](examples/app.py): run `python examples/app.py` and try
130
+ `HELLO_SERVER__PORT=9000`.
131
+
132
+ ## API
133
+
134
+ ```python
135
+ from tidyconf import Config, optional, ConfigError, KeyNotFoundError
136
+ ```
137
+
138
+ | API | Description |
139
+ | --- | --- |
140
+ | `Config(data=None)` | Create a config from a mapping (deep-copied). Handy in tests. |
141
+ | `Config.load(*sources, env_prefix=None)` | Load and deep-merge files in order (later wins), then apply env overrides if `env_prefix` is given. Env variables can only override keys defined in the files. |
142
+ | `optional(path)` | Mark a source file as optional: skipped if it does not exist. |
143
+ | `config.get(route, default=...)` | Value at a dotted route such as `"server.port"`. Returns a deep copy. Raises `KeyNotFoundError` if missing, unless `default` is given. |
144
+ | `config[route]` | Same as `config.get(route)` without a default. |
145
+ | `route in config` | Whether the route exists, e.g. `"database.port" in config`. Also `True` for keys set to `None`. |
146
+ | `config.set(route, value)` | Set a value, creating intermediate sections as needed. Raises `TypeError` if a part of the route is not a mapping. |
147
+ | `config.reset()` | Restore the state at construction / `load()` time. |
148
+ | `config.to_dict()` | Deep copy of all data as a plain `dict`. |
149
+
150
+ Because `get()` and `to_dict()` return copies, mutating a returned value never
151
+ changes the config; use `set()` for that.
152
+
153
+ File formats are chosen by suffix (case-insensitive): `.json`, `.toml`, `.yaml` / `.yml`.
154
+ Files are read as UTF-8 and the top level must be a mapping. An empty YAML file
155
+ counts as an empty mapping.
156
+
157
+ ### Errors
158
+
159
+ | Exception | When |
160
+ | --- | --- |
161
+ | `ConfigError` | Unsupported file type, parse error, top level not a mapping, YAML file without PyYAML installed, invalid env override. |
162
+ | `KeyNotFoundError` | Route not found in `get()` / `[]`. Subclass of both `ConfigError` and `KeyError`. |
163
+ | `FileNotFoundError` | A required (non-`optional`) source file does not exist. |
164
+ | `TypeError` | `set()` would have to go through a value that is not a mapping. |
165
+
166
+ ## Layering rules
167
+
168
+ - Sources are merged left to right; later sources win.
169
+ - If both sides have a mapping for the same key, they are merged recursively.
170
+ Any other value (including lists) is replaced as a whole, not combined.
171
+ - Environment overrides are applied last, on top of the merged files.
172
+ - `reset()` returns to this fully loaded state.
173
+
174
+ ## Environment variables
175
+
176
+ With `env_prefix="MYAPP"`, every environment variable starting with `MYAPP_` is an
177
+ override:
178
+
179
+ - The prefix is matched case-insensitively.
180
+ - The rest of the name is split on double underscores into a route:
181
+ `MYAPP_DATABASE__POOL_SIZE` sets `database.pool_size`. Single underscores are part
182
+ of the key.
183
+ - Each part matches an existing key case-insensitively.
184
+ - **The key must already exist in your config files.** Environment variables only
185
+ override values, they never add new ones. An unknown variable such as
186
+ `MYAPP_DATABSE__PORT` (note the typo) raises `ConfigError` at load time instead of
187
+ being silently ignored. Give every setting a default in your config file; for
188
+ secrets, use an empty placeholder like `password = ""`.
189
+ - Variables are applied in sorted order of their names.
190
+
191
+ Values are converted based on the type of the value that already exists at that
192
+ route:
193
+
194
+ | Existing value | Env value | Result |
195
+ | --- | --- | --- |
196
+ | `bool` | `true` / `1` / `yes` / `on`, `false` / `0` / `no` / `off` (any case) | `True` / `False` |
197
+ | `int` | `"9000"` | `9000` |
198
+ | `float` | `"0.5"` | `0.5` |
199
+ | `list` | JSON array, e.g. `'["search", "export"]'` | `["search", "export"]` |
200
+ | mapping (section) | anything | `ConfigError`: a whole section cannot be overridden |
201
+ | `str` or `None` | anything | the plain string |
202
+
203
+ A value that cannot be converted raises `ConfigError` naming the environment
204
+ variable, as does a route that runs through a non-mapping value.
205
+
206
+ ### Limitations
207
+
208
+ - Keys containing `.` cannot be reached with dotted routes (no escaping).
209
+ - Keys containing `.` or `-` cannot be set from environment variables: shells and
210
+ most tools do not allow those characters in variable names.
211
+ - An environment variable can only replace a single value, not a whole section or a
212
+ single list element.
213
+
214
+ ## Development
215
+
216
+ See [CLAUDE.md](CLAUDE.md) for setup, tests, linting and project conventions.
217
+
218
+ ## License
219
+
220
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ tidyconf/__init__.py,sha256=OKu6PcJEWiyQyue2xvD28xWjvBFmDxOloKZW4FIHaEw,261
2
+ tidyconf/config.py,sha256=Yo5dbw61D44xk326O_KuYCZHGoNbug6Gd-Bti1AmKhc,7242
3
+ tidyconf/exceptions.py,sha256=bP_8zq-jLbYfbnDbpwUXFr1uVi-q5GvUfayRonEQR-s,410
4
+ tidyconf/loaders.py,sha256=wIeq7uvrJnqMoS16dI1J-WugB0C8DSvV83-sK6nVwSM,1608
5
+ tidyconf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ tidyconf-1.0.0.dist-info/METADATA,sha256=_lklP7J-JU7IZ3vXoUI9ohfX9YuYDg0GhGePTcA27PA,7882
7
+ tidyconf-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ tidyconf-1.0.0.dist-info/licenses/LICENSE,sha256=U55ueSMAbMwqz5oqX9bpVIH-dEaxR7M_SaOCg-SS00s,1065
9
+ tidyconf-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 pgoelter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.