| 1 |
.. _Config Files: |
| 2 |
|
| 3 |
============ |
| 4 |
Config Files |
| 5 |
============ |
| 6 |
For more complicated CLI applications, it is common to have an external user configuration file. For example, the popular python tools ``poetry``, ``ruff``, and ``pytest`` are all configurable from a ``pyproject.toml`` file. The :attr:`App.config <cyclopts.App.config>` attribute accepts a `callable <https://docs.python.org/3/glossary.html#term-callable>`_ (or list of callables) that add (or remove) values to the parsed CLI tokens. The provided callable must have signature: |
| 7 |
|
| 8 |
.. code-block:: python |
| 9 |
|
| 10 |
def config(app: "App", commands: Tuple[str, ...], arguments: ArgumentCollection): |
| 11 |
"""Modifies the argument collection inplace with some injected values. |
| 12 |
|
| 13 |
Parameters |
| 14 |
---------- |
| 15 |
app: App |
| 16 |
The current command app being executed. |
| 17 |
commands: Tuple[str, ...] |
| 18 |
The CLI strings that led to the current command function. |
| 19 |
arguments: ArgumentCollection |
| 20 |
Complete ArgumentCollection for the app. |
| 21 |
Modify this collection inplace to influence values provided to the function. |
| 22 |
""" |
| 23 |
... |
| 24 |
|
| 25 |
The provided ``config`` does not have to be a function; all the Cyclopts builtin configs are classes that implement the ``__call__`` method. The Cyclopts builtins offer good standard functionality for common configuration files like yaml or toml. |
| 26 |
|
| 27 |
.. _TOML Example: |
| 28 |
|
| 29 |
------------ |
| 30 |
TOML Example |
| 31 |
------------ |
| 32 |
In this example, we create a small CLI tool that counts the number of times a given character occurs in a file. |
| 33 |
|
| 34 |
.. code-block:: python |
| 35 |
|
| 36 |
# character-counter.py |
| 37 |
import cyclopts |
| 38 |
from cyclopts import App |
| 39 |
from pathlib import Path |
| 40 |
|
| 41 |
app = App( |
| 42 |
name="character-counter", |
| 43 |
config=cyclopts.config.Toml( |
| 44 |
"pyproject.toml", # Name of the TOML File |
| 45 |
root_keys=["tool", "character-counter"], # The project's namespace in the TOML. |
| 46 |
# If "pyproject.toml" is not found in the current directory, |
| 47 |
# then iteratively search parenting directories until found. |
| 48 |
search_parents=True, |
| 49 |
), |
| 50 |
) |
| 51 |
|
| 52 |
@app.command |
| 53 |
def count(filename: Path, *, character="-"): |
| 54 |
print(filename.read_text().count(character)) |
| 55 |
|
| 56 |
if __name__ == "__main__": |
| 57 |
app() |
| 58 |
|
| 59 |
Running this code without a ``pyproject.toml`` present: |
| 60 |
|
| 61 |
.. code-block:: console |
| 62 |
|
| 63 |
$ python character-counter.py count README.md |
| 64 |
70 |
| 65 |
$ python character-counter.py count README.md --character=t |
| 66 |
380 |
| 67 |
|
| 68 |
We can have the new default character be ``t`` by adding the following to ``pyproject.toml``: |
| 69 |
|
| 70 |
.. code-block:: toml |
| 71 |
|
| 72 |
[tool.character-counter.count] |
| 73 |
character = "t" |
| 74 |
|
| 75 |
Rerunning the app without a specified ``--character`` will result in using the toml-provided value: |
| 76 |
|
| 77 |
.. code-block:: console |
| 78 |
|
| 79 |
$ python character-counter.py count README.md |
| 80 |
380 |
| 81 |
|
| 82 |
-------------------------- |
| 83 |
User-Specified Config File |
| 84 |
-------------------------- |
| 85 |
Extending the above :ref:`TOML Example`, what if we want to allow the user to specify the toml configuration file? |
| 86 |
This can be accomplished via a :ref:`Meta App`. |
| 87 |
|
| 88 |
.. code-block:: python |
| 89 |
|
| 90 |
# character-counter.py |
| 91 |
from pathlib import Path |
| 92 |
from typing import Annotated |
| 93 |
|
| 94 |
import cyclopts |
| 95 |
from cyclopts import App, Parameter |
| 96 |
|
| 97 |
app = App(name="character-counter") |
| 98 |
|
| 99 |
@app.command |
| 100 |
def count(filename: Path, *, character="-"): |
| 101 |
print(filename.read_text().count(character)) |
| 102 |
|
| 103 |
@app.meta.default |
| 104 |
def meta( |
| 105 |
*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)], |
| 106 |
config: Path = Path("pyproject.toml"), |
| 107 |
): |
| 108 |
app.config = cyclopts.config.Toml( |
| 109 |
config, |
| 110 |
root_keys=["tool", "character-counter"], |
| 111 |
search_parents=True, |
| 112 |
) |
| 113 |
|
| 114 |
app(tokens) |
| 115 |
|
| 116 |
if __name__ == "__main__": |
| 117 |
app.meta() |
| 118 |
|
| 119 |
---------------------------- |
| 120 |
Environment Variable Example |
| 121 |
---------------------------- |
| 122 |
To automatically derive and read appropriate environment variables, use the :class:`cyclopts.config.Env` class. Continuing the above TOML example: |
| 123 |
|
| 124 |
|
| 125 |
.. code-block:: python |
| 126 |
|
| 127 |
# character-counter.py |
| 128 |
import cyclopts |
| 129 |
from pathlib import Path |
| 130 |
|
| 131 |
app = cyclopts.App( |
| 132 |
name="character-counter", |
| 133 |
config=cyclopts.config.Env( |
| 134 |
"CHAR_COUNTER_", # Every environment variable will begin with this. |
| 135 |
), |
| 136 |
) |
| 137 |
|
| 138 |
@app.command |
| 139 |
def count(filename: Path, *, character="-"): |
| 140 |
print(filename.read_text().count(character)) |
| 141 |
|
| 142 |
app() |
| 143 |
|
| 144 |
:class:`~cyclopts.config.Env` assembles the environment variable name by joining the following components (in-order): |
| 145 |
|
| 146 |
1. The provided ``prefix``. In this case, it is ``"CHAR_COUNTER_"``. |
| 147 |
|
| 148 |
2. The command and subcommand(s) that lead up to the function being executed. |
| 149 |
|
| 150 |
3. The parameter's CLI name, with the leading ``--`` stripped, and hyphens ``-`` replaced with underscores ``_``. |
| 151 |
|
| 152 |
Running this code without a specified ``--character`` results in counting the default ``-`` character. |
| 153 |
|
| 154 |
.. code-block:: console |
| 155 |
|
| 156 |
$ python character-counter.py count README.md |
| 157 |
70 |
| 158 |
|
| 159 |
By exporting a value to ``CHAR_COUNTER_COUNT_CHARACTER``, that value will now be used as the default: |
| 160 |
|
| 161 |
.. code-block:: console |
| 162 |
|
| 163 |
$ export CHAR_COUNTER_COUNT_CHARACTER=t |
| 164 |
$ python character-counter.py count README.md |
| 165 |
380 |
| 166 |
$ python character-counter.py count README.md --character=q |
| 167 |
3 |
| 168 |
|
| 169 |
-------------- |
| 170 |
In-Memory Dict |
| 171 |
-------------- |
| 172 |
For configurations that come from sources other than files, use :class:`cyclopts.config.Dict`. |
| 173 |
|
| 174 |
.. code-block:: python |
| 175 |
|
| 176 |
# character-counter.py |
| 177 |
import json |
| 178 |
import cyclopts |
| 179 |
from pathlib import Path |
| 180 |
|
| 181 |
def fetch_config(): |
| 182 |
"""Simulate fetching configuration from an API.""" |
| 183 |
return {"count": {"character": "e"}} |
| 184 |
|
| 185 |
config_data = fetch_config_from_api() |
| 186 |
|
| 187 |
app = cyclopts.App( |
| 188 |
name="character-counter", |
| 189 |
config=cyclopts.config.Dict( |
| 190 |
fetch_config, |
| 191 |
# Optional: provide custom source identifier for better error messages |
| 192 |
source="api", |
| 193 |
), |
| 194 |
) |
| 195 |
|
| 196 |
@app.command |
| 197 |
def count(filename: Path, *, character="-"): |
| 198 |
print(filename.read_text().count(character)) |
| 199 |
|
| 200 |
if __name__ == "__main__": |
| 201 |
app() |
| 202 |
|
| 203 |
--------------------------------- |
| 204 |
Combining Multiple Config Sources |
| 205 |
--------------------------------- |
| 206 |
|
| 207 |
You can combine multiple config sources in a single application by passing a sequence to :attr:`App.config <cyclopts.App.config>`. Each configuration is applied sequentially. |
| 208 |
|
| 209 |
In the following example, we combine a TOML file and environment variables, allowing environment variables to override TOML settings: |
| 210 |
|
| 211 |
.. code-block:: python |
| 212 |
|
| 213 |
# character-counter.py |
| 214 |
import cyclopts |
| 215 |
from pathlib import Path |
| 216 |
|
| 217 |
app = cyclopts.App( |
| 218 |
name="character-counter", |
| 219 |
config=[ |
| 220 |
# Since Env comes before Toml, it has priority. |
| 221 |
cyclopts.config.Env("CHAR_COUNTER_"), |
| 222 |
cyclopts.config.Toml( |
| 223 |
"pyproject.toml", |
| 224 |
root_keys=["tool", "character-counter"], |
| 225 |
search_parents=True, |
| 226 |
), |
| 227 |
], |
| 228 |
) |
| 229 |
|
| 230 |
@app.command |
| 231 |
def count(filename: Path, *, character="-"): |
| 232 |
print(filename.read_text().count(character)) |
| 233 |
|
| 234 |
if __name__ == "__main__": |
| 235 |
app() |
| 236 |
|
| 237 |
With this setup, the configuration is resolved in the following order: |
| 238 |
|
| 239 |
1. **CLI arguments** (if provided) override everything else |
| 240 |
2. **Environment variables** (prefixed with ``CHAR_COUNTER_``) can override TOML values |
| 241 |
3. **TOML file** (pyproject.toml) provides the base configuration |
| 242 |
4. **Python default** the default value ``-`` in the python code. |
| 243 |
|
| 244 |
For example, with ``pyproject.toml`` containing: |
| 245 |
|
| 246 |
.. code-block:: toml |
| 247 |
|
| 248 |
[tool.character-counter.count] |
| 249 |
character = "t" |
| 250 |
|
| 251 |
You can override it via environment variable: |
| 252 |
|
| 253 |
.. code-block:: console |
| 254 |
|
| 255 |
$ CHAR_COUNTER_COUNT_CHARACTER=a python character-counter.py count README.md |
| 256 |
|
| 257 |
Or via CLI argument: |
| 258 |
|
| 259 |
.. code-block:: console |
| 260 |
|
| 261 |
$ python character-counter.py count README.md --character=x |