| 1 |
.. _Coercion Rules: |
| 2 |
|
| 3 |
============== |
| 4 |
Coercion Rules |
| 5 |
============== |
| 6 |
This page intends to serve as a terse set of type coercion rules that Cyclopts follows. |
| 7 |
|
| 8 |
Automatic coercion can always be overridden by the :attr:`.Parameter.converter` field. |
| 9 |
Typically, the :attr:`~.Parameter.converter` function will receive a single token, but it may receive multiple tokens |
| 10 |
if the annotated type is iterable (e.g. :class:`list`, :class:`set`). |
| 11 |
The number of tokens can be explicitly controlled with :attr:`~.Parameter.n_tokens`, which is useful when the |
| 12 |
type signature doesn't match the desired CLI token consumption. |
| 13 |
|
| 14 |
******* |
| 15 |
No Hint |
| 16 |
******* |
| 17 |
If no explicit type hint is provided: |
| 18 |
|
| 19 |
* If the parameter has a **non-None** default value, interpret the type as ``type(default_value)``. |
| 20 |
|
| 21 |
.. code-block:: python |
| 22 |
|
| 23 |
from cyclopts import App |
| 24 |
|
| 25 |
app = App() |
| 26 |
|
| 27 |
@app.default |
| 28 |
def default(value=5): |
| 29 |
print(f"{value=} {type(value)=}") |
| 30 |
|
| 31 |
app() |
| 32 |
|
| 33 |
.. code-block:: console |
| 34 |
|
| 35 |
$ my-program 3 |
| 36 |
value=3 type(value)=<class 'int'> |
| 37 |
|
| 38 |
* Otherwise, :ref:`interpret the type as string <Coercion Rules - Str>`. |
| 39 |
|
| 40 |
.. code-block:: python |
| 41 |
|
| 42 |
from cyclopts import App |
| 43 |
|
| 44 |
app = App() |
| 45 |
|
| 46 |
@app.default |
| 47 |
def default(value): |
| 48 |
print(f"{value=} {type(value)=}") |
| 49 |
|
| 50 |
app() |
| 51 |
|
| 52 |
.. code-block:: console |
| 53 |
|
| 54 |
$ my-program foo |
| 55 |
value='foo' type(value)=<class 'str'> |
| 56 |
|
| 57 |
*** |
| 58 |
Any |
| 59 |
*** |
| 60 |
A standalone ``Any`` type hint is equivalent to `No Hint`_ |
| 61 |
|
| 62 |
.. _Coercion Rules - Str: |
| 63 |
|
| 64 |
*** |
| 65 |
Str |
| 66 |
*** |
| 67 |
No operation is performed, CLI tokens are natively strings. |
| 68 |
|
| 69 |
.. code-block:: python |
| 70 |
|
| 71 |
from cyclopts import App |
| 72 |
|
| 73 |
app = App() |
| 74 |
|
| 75 |
@app.default |
| 76 |
def default(value: str): |
| 77 |
print(f"{value=} {type(value)=}") |
| 78 |
|
| 79 |
app() |
| 80 |
|
| 81 |
.. code-block:: console |
| 82 |
|
| 83 |
$ my-program foo |
| 84 |
value='foo' type(value)=<class 'str'> |
| 85 |
|
| 86 |
*** |
| 87 |
Int |
| 88 |
*** |
| 89 |
For convenience, Cyclopts provides a richer feature-set of parsing integers than just naively calling ``int``. |
| 90 |
|
| 91 |
* Accepts vanilla decimal values (e.g. ``123``, ``3.1415``). Floating-point values will be rounded prior to casting to an ``int``. |
| 92 |
* Accepts binary values (strings starting with ``0b``) |
| 93 |
* Accepts octal values (strings starting with ``0o``) |
| 94 |
* Accepts hexadecimal values (strings starting with ``0x``). |
| 95 |
|
| 96 |
^^^^^^^^^^^^^^ |
| 97 |
Counting Flags |
| 98 |
^^^^^^^^^^^^^^ |
| 99 |
For parameters that need to track the number of times a flag appears (e.g., verbosity levels like ``-vvv``), use :attr:`.Parameter.count` with an :obj:`int` type hint. |
| 100 |
|
| 101 |
.. code-block:: python |
| 102 |
|
| 103 |
from cyclopts import App, Parameter |
| 104 |
from typing import Annotated |
| 105 |
|
| 106 |
app = App() |
| 107 |
|
| 108 |
@app.default |
| 109 |
def main(verbose: Annotated[int, Parameter(alias="-v", count=True)] = 0): |
| 110 |
print(f"Verbosity level: {verbose}") |
| 111 |
|
| 112 |
app() |
| 113 |
|
| 114 |
.. code-block:: console |
| 115 |
|
| 116 |
$ my-program |
| 117 |
Verbosity level: 0 |
| 118 |
|
| 119 |
$ my-program -v |
| 120 |
Verbosity level: 1 |
| 121 |
|
| 122 |
$ my-program -vvv |
| 123 |
Verbosity level: 3 |
| 124 |
|
| 125 |
$ my-program --verbose --verbose |
| 126 |
Verbosity level: 2 |
| 127 |
|
| 128 |
$ my-program -v --verbose -vv |
| 129 |
Verbosity level: 4 |
| 130 |
|
| 131 |
***** |
| 132 |
Float |
| 133 |
***** |
| 134 |
Token gets cast as ``float(token)``. For example, ``float("3.14")``. |
| 135 |
|
| 136 |
******* |
| 137 |
Complex |
| 138 |
******* |
| 139 |
Token gets cast as ``complex(token)``. For example, ``complex("3+5j")`` |
| 140 |
|
| 141 |
**** |
| 142 |
Bool |
| 143 |
**** |
| 144 |
1. If specified as a **keyword**, booleans are interpreted flags that take no parameter. |
| 145 |
The default **false-like** flag are ``--no-FLAG-NAME``. |
| 146 |
See :attr:`.Parameter.negative` for more about this feature. |
| 147 |
|
| 148 |
Example: |
| 149 |
|
| 150 |
.. code-block:: python |
| 151 |
|
| 152 |
from cyclopts import App |
| 153 |
|
| 154 |
app = App() |
| 155 |
|
| 156 |
@app.command |
| 157 |
def foo(my_flag: bool): |
| 158 |
print(my_flag) |
| 159 |
|
| 160 |
app() |
| 161 |
|
| 162 |
.. code-block:: console |
| 163 |
|
| 164 |
$ my-program foo --my-flag |
| 165 |
True |
| 166 |
|
| 167 |
$ my-program foo --no-my-flag |
| 168 |
False |
| 169 |
|
| 170 |
2. If specified as a **positional** argument, a case-insensitive lookup is performed: |
| 171 |
|
| 172 |
* If the token is a **true-like value** ``{"yes", "y", "1", "true", "t"}``, then it is parsed as :obj:`True`. |
| 173 |
|
| 174 |
* If the token is a **false-like value** ``{"no", "n", "0", "false", "f"}``, then it is parsed as :obj:`False`. |
| 175 |
|
| 176 |
* Otherwise, a :exc:`.CoercionError` will be raised. |
| 177 |
|
| 178 |
Cyclopts is stricter than traditional :class:`bool` casting; the provided value **must** be one of the above. For example, ``2`` is **not** considered a true-like value and will raise an error. |
| 179 |
|
| 180 |
.. code-block:: console |
| 181 |
|
| 182 |
$ my-program foo 1 |
| 183 |
True |
| 184 |
|
| 185 |
$ my-program foo 0 |
| 186 |
False |
| 187 |
|
| 188 |
$ my-program foo 2 |
| 189 |
╭─ Error ───────────────────────────────────────╮ |
| 190 |
│ Invalid value for --my-flag: unable to │ |
| 191 |
│ convert "2" into bool. │ |
| 192 |
╰───────────────────────────────────────────────╯ |
| 193 |
|
| 194 |
$ my-program foo not-a-true-or-false-value |
| 195 |
╭─ Error ─────────────────────────────────────────────────╮ |
| 196 |
│ Invalid value for --my-flag: unable to convert │ |
| 197 |
│ "not-a-true-or-false-value" into bool. │ |
| 198 |
╰─────────────────────────────────────────────────────────╯ |
| 199 |
|
| 200 |
|
| 201 |
3. If specified as a keyword with a value attached with an ``=``, then the provided value will be parsed according to positional argument rules above (2). |
| 202 |
|
| 203 |
.. code-block:: python |
| 204 |
|
| 205 |
from cyclopts import App |
| 206 |
|
| 207 |
app = App() |
| 208 |
|
| 209 |
@app.command |
| 210 |
def foo(my_flag: bool): |
| 211 |
print(my_flag) |
| 212 |
|
| 213 |
app() |
| 214 |
|
| 215 |
.. code-block:: console |
| 216 |
|
| 217 |
$ my-program foo --my-flag=true |
| 218 |
True |
| 219 |
|
| 220 |
$ my-program foo --my-flag=false |
| 221 |
False |
| 222 |
|
| 223 |
$ my-program foo --no-my-flag=true |
| 224 |
False |
| 225 |
|
| 226 |
$ my-program foo --no-my-flag=false |
| 227 |
True |
| 228 |
|
| 229 |
|
| 230 |
**** |
| 231 |
List |
| 232 |
**** |
| 233 |
Unlike more simple types like :obj:`str` and :obj:`int`, lists use different parsing rules depending on whether the values are provided positionally or by keyword. |
| 234 |
|
| 235 |
^^^^^^^^^^ |
| 236 |
Positional |
| 237 |
^^^^^^^^^^ |
| 238 |
When arguments are provided positionally: |
| 239 |
|
| 240 |
* If :attr:`.Parameter.allow_leading_hyphen` is :obj:`False` (default behavior), reaching an option-like token will stop parsing for this parameter. |
| 241 |
If the number of consumed tokens is not a multiple of the required number of tokens to create an element of the list, a :exc:`.MissingArgumentError` will be raised. |
| 242 |
|
| 243 |
.. code-block:: python |
| 244 |
|
| 245 |
from cyclopts import App |
| 246 |
|
| 247 |
app = App() |
| 248 |
|
| 249 |
@app.command |
| 250 |
def foo(values: list[int]): # 1 CLI token per element |
| 251 |
print(values) |
| 252 |
|
| 253 |
@app.command |
| 254 |
def bar(values: list[tuple[int, str]]): # 2 CLI tokens per element |
| 255 |
print(values) |
| 256 |
|
| 257 |
app() |
| 258 |
|
| 259 |
.. code-block:: console |
| 260 |
|
| 261 |
$ my-program foo 1 2 3 |
| 262 |
[1, 2, 3] |
| 263 |
|
| 264 |
$ my-program bar 1 one 2 two |
| 265 |
[(1, 'one'), (2, 'two')] |
| 266 |
|
| 267 |
$ my-program bar 1 one 2 |
| 268 |
╭─ Error ─────────────────────────────────────────────────────╮ |
| 269 |
│ Command "bar" parameter "--values" requires 2 arguments. │ |
| 270 |
│ Only got 1. │ |
| 271 |
╰─────────────────────────────────────────────────────────────╯ |
| 272 |
|
| 273 |
* If :attr:`.Parameter.allow_leading_hyphen` is :obj:`True`, CLI tokens will be consumed unconditionally until exhausted. |
| 274 |
|
| 275 |
.. code-block:: python |
| 276 |
|
| 277 |
from cyclopts import App, Parameter |
| 278 |
from pathlib import Path |
| 279 |
from typing import Annotated |
| 280 |
|
| 281 |
app = App() |
| 282 |
|
| 283 |
@app.default |
| 284 |
def main( |
| 285 |
files: Annotated[list[Path], Parameter(allow_leading_hyphen=True)], |
| 286 |
some_flag: bool = False, |
| 287 |
): |
| 288 |
print(f"{some_flag=}") |
| 289 |
print(f"Analyzing files {files}") |
| 290 |
|
| 291 |
app() |
| 292 |
|
| 293 |
.. code-block:: console |
| 294 |
|
| 295 |
$ my-program foo.bin bar.bin --fizz.bin buzz.bin --some-flag |
| 296 |
some_flag=True |
| 297 |
Analyzing files [PosixPath('foo.bin'), PosixPath('bar.bin'), PosixPath('--fizz.bin'), PosixPath('buzz.bin')] |
| 298 |
|
| 299 |
Known keyword arguments are parsed first (in this case, ``--some-flag``). |
| 300 |
To unambiguously pass in values positionally, provide them after a bare ``--``: |
| 301 |
|
| 302 |
.. code-block:: console |
| 303 |
|
| 304 |
$ my-program -- foo.bin bar.bin --fizz.bin buzz.bin --some-flag |
| 305 |
some_flag=False |
| 306 |
Analyzing files [PosixPath('foo.bin'), PosixPath('bar.bin'), PosixPath('--fizz.bin'), PosixPath('buzz.bin'), PosixPath('--some-flag')] |
| 307 |
|
| 308 |
|
| 309 |
^^^^^^^ |
| 310 |
Keyword |
| 311 |
^^^^^^^ |
| 312 |
When arguments are provided by keyword: |
| 313 |
|
| 314 |
* Tokens will be consumed until enough data is collected to form the type-hinted object. |
| 315 |
|
| 316 |
* The keyword can be specified multiple times. |
| 317 |
|
| 318 |
* If :attr:`.Parameter.allow_leading_hyphen` is :obj:`False` (default behavior), reaching an option-like token will raise :exc:`.MissingArgumentError` if insufficient tokens have been parsed. |
| 319 |
|
| 320 |
.. code-block:: python |
| 321 |
|
| 322 |
from cyclopts import App |
| 323 |
|
| 324 |
app = App() |
| 325 |
|
| 326 |
@app.command |
| 327 |
def foo(values: list[int]): # 1 CLI token per element |
| 328 |
print(values) |
| 329 |
|
| 330 |
@app.command |
| 331 |
def bar(values: list[tuple[int, str]]): # 2 CLI tokens per element |
| 332 |
print(values) |
| 333 |
|
| 334 |
app() |
| 335 |
|
| 336 |
.. code-block:: console |
| 337 |
|
| 338 |
$ my-program foo --values 1 --values 2 --values 3 |
| 339 |
[1, 2, 3] |
| 340 |
|
| 341 |
$ my-program bar --values 1 one --values 2 two |
| 342 |
[(1, 'one'), (2, 'two')] |
| 343 |
|
| 344 |
$ my-program bar --values 1 --values 2 |
| 345 |
╭─ Error ─────────────────────────────────────────────────────╮ |
| 346 |
│ Command "bar" parameter "--values" requires 2 arguments. │ |
| 347 |
│ Only got 1. │ |
| 348 |
╰─────────────────────────────────────────────────────────────╯ |
| 349 |
|
| 350 |
|
| 351 |
* If :attr:`.Parameter.consume_multiple` is :obj:`True`, all remaining tokens will be consumed (until an option-like token is reached if :attr:`.Parameter.allow_leading_hyphen` is :obj:`False`). |
| 352 |
|
| 353 |
:attr:`.Parameter.consume_multiple` also accepts an :class:`int` (minimum element count) or a ``tuple[int, int]`` for ``(min, max)`` bounds. See the :attr:`.Parameter.consume_multiple` API docs for details. |
| 354 |
|
| 355 |
.. code-block:: python |
| 356 |
|
| 357 |
from cyclopts import App, Parameter |
| 358 |
from typing import Annotated |
| 359 |
|
| 360 |
app = App() |
| 361 |
|
| 362 |
@app.default |
| 363 |
def foo(values: Annotated[list[int], Parameter(consume_multiple=True)]): # 1 CLI token per element |
| 364 |
print(values) |
| 365 |
|
| 366 |
app() |
| 367 |
|
| 368 |
.. code-block:: console |
| 369 |
|
| 370 |
$ my-program foo --values 1 2 3 |
| 371 |
[1, 2, 3] |
| 372 |
|
| 373 |
* If :attr:`.Parameter.allow_repeating` is :obj:`False`, a keyword option cannot be specified more than once. |
| 374 |
This is especially useful in combination with :attr:`.Parameter.consume_multiple` to allow ``--foo a b c`` but reject ``--foo a --foo b``. |
| 375 |
If :attr:`.Parameter.allow_repeating` is :obj:`True`, scalar types use "last wins" semantics instead of raising an error. |
| 376 |
|
| 377 |
.. code-block:: python |
| 378 |
|
| 379 |
from cyclopts import App, Parameter |
| 380 |
from typing import Annotated |
| 381 |
|
| 382 |
app = App() |
| 383 |
|
| 384 |
@app.default |
| 385 |
def foo(values: Annotated[list[int], Parameter(consume_multiple=True, allow_repeating=False)]): |
| 386 |
print(values) |
| 387 |
|
| 388 |
app() |
| 389 |
|
| 390 |
.. code-block:: console |
| 391 |
|
| 392 |
$ my-program --values 1 2 3 |
| 393 |
[1, 2, 3] |
| 394 |
|
| 395 |
$ my-program --values 1 --values 2 |
| 396 |
╭─ Error ──────────────────────────────────────────────────╮ |
| 397 |
│ Parameter --values specified multiple times. │ |
| 398 |
╰─────────────────────────────────────────────────────────╯ |
| 399 |
|
| 400 |
^^^^^^^^^^ |
| 401 |
Empty List |
| 402 |
^^^^^^^^^^ |
| 403 |
Commonly, if we want a default list for a parameter in a function, we set the default value to ``None`` in the signature and then set it to the actual list in the function body: |
| 404 |
|
| 405 |
.. code-block:: python |
| 406 |
|
| 407 |
def foo(extensions: Optional[list] = None): |
| 408 |
if extensions is None: |
| 409 |
extensions = [".png", ".jpg"] |
| 410 |
|
| 411 |
We do this because mutable defaults is a `common unexpected source of bugs in python <https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments>`_. |
| 412 |
|
| 413 |
However, sometimes we actually want to specify an empty list. |
| 414 |
To get an empty list pass in the flag ``--empty-MY-LIST-NAME``. |
| 415 |
|
| 416 |
.. code-block:: python |
| 417 |
|
| 418 |
from cyclopts import App |
| 419 |
|
| 420 |
app = App() |
| 421 |
|
| 422 |
@app.default |
| 423 |
def main(extensions: list | None = None): |
| 424 |
if extensions is None: |
| 425 |
extensions = [".png", ".jpg"] |
| 426 |
print(f"{extensions=}") |
| 427 |
|
| 428 |
app() |
| 429 |
|
| 430 |
.. code-block:: console |
| 431 |
|
| 432 |
$ my-program |
| 433 |
extensions=['.png', '.jpg'] |
| 434 |
|
| 435 |
$ my-program --empty-extensions |
| 436 |
extensions=[] |
| 437 |
|
| 438 |
See :attr:`.Parameter.negative` for more about this feature. |
| 439 |
|
| 440 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 441 |
Positional Only With Subsequent Parameters |
| 442 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 443 |
When a list is **positional-only**, it will consume tokens such that it leaves enough tokens for subsequent positional-only parameters. |
| 444 |
|
| 445 |
.. code-block:: python |
| 446 |
|
| 447 |
from pathlib import Path |
| 448 |
from cyclopts import App |
| 449 |
|
| 450 |
app = App() |
| 451 |
|
| 452 |
@app.default |
| 453 |
def main(srcs: list[Path], dst: Path, /): # "/" makes all prior parameters POSITIONAL_ONLY |
| 454 |
print(f"Processing files {srcs!r} to {dst!r}.") |
| 455 |
|
| 456 |
app() |
| 457 |
|
| 458 |
.. code-block:: console |
| 459 |
|
| 460 |
$ my-program foo.bin bar.bin output.bin |
| 461 |
Processing files [PosixPath('foo.bin'), PosixPath('bar.bin')] to PosixPath('output.bin'). |
| 462 |
|
| 463 |
|
| 464 |
The console wildcard ``*`` is expanded by the console, so this example will naturally work with wildcards. |
| 465 |
|
| 466 |
.. code-block:: console |
| 467 |
|
| 468 |
$ ls foo |
| 469 |
buzz.bin fizz.bin |
| 470 |
|
| 471 |
$ my-program foo/*.bin output.bin |
| 472 |
Processing files [PosixPath('foo/buzz.bin'), PosixPath('foo/fizz.bin')] to PosixPath('output.bin'). |
| 473 |
|
| 474 |
|
| 475 |
******** |
| 476 |
Iterable |
| 477 |
******** |
| 478 |
Follows the same rules as `List`_. The passed in data will be a :class:`list`. |
| 479 |
|
| 480 |
******** |
| 481 |
Sequence |
| 482 |
******** |
| 483 |
Follows the same rules as `List`_. The passed in data will be a :class:`list`. |
| 484 |
|
| 485 |
*** |
| 486 |
Set |
| 487 |
*** |
| 488 |
Follows the same rules as `List`_, but the resulting datatype is a :class:`set`. |
| 489 |
|
| 490 |
********* |
| 491 |
Frozenset |
| 492 |
********* |
| 493 |
Follows the same rules as `Set`_, but the resulting datatype is a :class:`frozenset`. |
| 494 |
|
| 495 |
***** |
| 496 |
Tuple |
| 497 |
***** |
| 498 |
* The inner type hint(s) will be applied independently to each element. Enough CLI tokens will be consumed to populate the inner types. |
| 499 |
|
| 500 |
* Nested fixed-length tuples are allowed: E.g. ``tuple[tuple[int, str], str]`` will consume 3 CLI tokens. |
| 501 |
|
| 502 |
* Indeterminite-size tuples ``tuple[type, ...]`` are only supported at the root-annotation level and behave similarly to `List`_. |
| 503 |
|
| 504 |
.. code-block:: python |
| 505 |
|
| 506 |
from cyclopts import App |
| 507 |
|
| 508 |
app = App() |
| 509 |
|
| 510 |
@app.default |
| 511 |
def default(coordinates: tuple[float, float, str]): |
| 512 |
print(f"{coordinates=}") |
| 513 |
|
| 514 |
app() |
| 515 |
|
| 516 |
And invoke our script: |
| 517 |
|
| 518 |
.. code-block:: console |
| 519 |
|
| 520 |
$ my-program --coordinates 3.14 2.718 my-coord-name |
| 521 |
coordinates=(3.14, 2.718, 'my-coord-name') |
| 522 |
|
| 523 |
.. _Coercion Rules - Union: |
| 524 |
|
| 525 |
**** |
| 526 |
Dict |
| 527 |
**** |
| 528 |
Cyclopts can populate dictionaries using keyword dot-notation: |
| 529 |
|
| 530 |
.. code-block:: python |
| 531 |
|
| 532 |
from cyclopts import App |
| 533 |
|
| 534 |
app = App() |
| 535 |
|
| 536 |
@app.default |
| 537 |
def default(message: str, *, mapping: dict[str, str] | None = None): |
| 538 |
if mapping: |
| 539 |
for find, replace in mapping.items(): |
| 540 |
message = message.replace(find, replace) |
| 541 |
print(message) |
| 542 |
|
| 543 |
app() |
| 544 |
|
| 545 |
.. code-block:: console |
| 546 |
|
| 547 |
$ my_program 'Hello Cyclopts users!' |
| 548 |
Hello Cyclopts users! |
| 549 |
|
| 550 |
$ my_program 'Hello Cyclopts users!' --mapping.Hello Hey |
| 551 |
Hey Cyclopts users! |
| 552 |
|
| 553 |
$ my_program 'Hello Cyclopts users!' --mapping.Hello Hey --mapping.users developers |
| 554 |
Hey Cyclopts developers! |
| 555 |
|
| 556 |
Due to the way of specifying keys, it is recommended to make dict parameters keyword-only; dicts **cannot** be populated positionally. |
| 557 |
If you do not wish for the user to be able to specify arbitrary keys, see `User-Defined Classes`_. |
| 558 |
For specifying arbitrary keywords at the root level, see :ref:`kwargs <Args & Kwargs - Kwargs>`. |
| 559 |
|
| 560 |
***** |
| 561 |
Union |
| 562 |
***** |
| 563 |
|
| 564 |
The unioned types will be iterated **left-to-right** until a successful coercion is performed. |
| 565 |
:obj:`None` type hints are ignored. |
| 566 |
|
| 567 |
.. code-block:: python |
| 568 |
|
| 569 |
from cyclopts import App |
| 570 |
from typing import Union |
| 571 |
|
| 572 |
app = App() |
| 573 |
|
| 574 |
@app.default |
| 575 |
def default(a: Union[None, int, str]): |
| 576 |
print(type(a)) |
| 577 |
|
| 578 |
app() |
| 579 |
|
| 580 |
.. code-block:: console |
| 581 |
|
| 582 |
$ my-program 10 |
| 583 |
<class 'int'> |
| 584 |
|
| 585 |
$ my-program bar |
| 586 |
<class 'str'> |
| 587 |
|
| 588 |
|
| 589 |
******** |
| 590 |
Optional |
| 591 |
******** |
| 592 |
``Optional[...]`` is syntactic sugar for ``Union[..., None]``. See Union_ rules. |
| 593 |
|
| 594 |
.. _Coercion Rules - Literal: |
| 595 |
|
| 596 |
******* |
| 597 |
Literal |
| 598 |
******* |
| 599 |
The :obj:`~typing.Literal` type is a good option for limiting user input to a set of choices. |
| 600 |
Like Union_, the :obj:`~typing.Literal` options will be iterated **left-to-right** until a successful coercion is performed. |
| 601 |
Cyclopts attempts to coerce the input token into the **type** of each :obj:`~typing.Literal` option. |
| 602 |
|
| 603 |
|
| 604 |
.. code-block:: python |
| 605 |
|
| 606 |
from cyclopts import App |
| 607 |
from typing import Literal |
| 608 |
|
| 609 |
app = App() |
| 610 |
|
| 611 |
@app.default |
| 612 |
def default(value: Literal["foo", "bar", 3]): |
| 613 |
print(f"{value=} {type(value)=}") |
| 614 |
|
| 615 |
app() |
| 616 |
|
| 617 |
.. code-block:: console |
| 618 |
|
| 619 |
$ my-program foo |
| 620 |
value='foo' type(value)=<class 'str'> |
| 621 |
|
| 622 |
$ my-program bar |
| 623 |
value='bar' type(value)=<class 'str'> |
| 624 |
|
| 625 |
$ my-program 3 |
| 626 |
value=3 type(value)=<class 'int'> |
| 627 |
|
| 628 |
$ my-program fizz |
| 629 |
╭─ Error ─────────────────────────────────────────────────╮ |
| 630 |
│ Invalid value "fizz" for VALUE. Choose from: "foo", │ |
| 631 |
│ "bar", 3. │ |
| 632 |
╰─────────────────────────────────────────────────────────╯ |
| 633 |
|
| 634 |
|
| 635 |
**** |
| 636 |
Enum |
| 637 |
**** |
| 638 |
While `Literal`_ is the recommended way of providing the user a set of choices, another method is using :class:`~enum.Enum`. |
| 639 |
|
| 640 |
The :attr:`Parameter.name_transform <cyclopts.Parameter.name_transform>` gets applied to all :class:`~enum.Enum` names, as well as the CLI provided token. |
| 641 |
By default,this means that a **case-insensitive name** lookup is performed. |
| 642 |
If an enum name contains an underscore, the CLI parameter **may** instead contain a hyphen, ``-``. |
| 643 |
Leading/Trailing underscores will be stripped. |
| 644 |
|
| 645 |
If coming from Typer_, **Cyclopts Enum handling is the reverse of Typer**. |
| 646 |
Typer attempts to match the token to an Enum **value**; Cyclopts attempts to match the token to an Enum **name**. |
| 647 |
This is done because generally the **name** of the enum is meant to be human readable, while the **value** has some program/machine significance. |
| 648 |
|
| 649 |
As a real-world example, the PNG image format supports `5 different color-types <https://www.w3.org/TR/2003/REC-PNG-20031110/#6Colour-values>`_, which gets encoded into a `1-byte int in the image header <https://www.w3.org/TR/2003/REC-PNG-20031110/#11IHDR>`_. |
| 650 |
|
| 651 |
.. code-block:: python |
| 652 |
|
| 653 |
from cyclopts import App |
| 654 |
from enum import IntEnum |
| 655 |
|
| 656 |
app = App() |
| 657 |
|
| 658 |
class ColorType(IntEnum): |
| 659 |
GRAYSCALE = 0 |
| 660 |
RGB = 2 |
| 661 |
PALETTE = 3 |
| 662 |
GRAYSCALE_ALPHA = 4 |
| 663 |
RGBA = 6 |
| 664 |
|
| 665 |
@app.default |
| 666 |
def default(color_type: ColorType = ColorType.RGB): |
| 667 |
print(f"Writing color-type value: {color_type} to the image header.") |
| 668 |
|
| 669 |
app() |
| 670 |
|
| 671 |
.. code-block:: console |
| 672 |
|
| 673 |
$ my-program |
| 674 |
Writing color-type value: 2 to the image header. |
| 675 |
|
| 676 |
$ my-program grayscale-alpha |
| 677 |
Writing color-type value: 4 to the image header. |
| 678 |
|
| 679 |
**** |
| 680 |
Flag |
| 681 |
**** |
| 682 |
:class:`~enum.Flag` enums (and by extension, :class:`~enum.IntFlag`) are treated as a collection of boolean flags. |
| 683 |
|
| 684 |
The :attr:`Parameter.name_transform <cyclopts.Parameter.name_transform>` gets applied to all :class:`~enum.Flag` names, as well as the CLI provided token. |
| 685 |
By default, this means that a **case-insensitive name** lookup is performed. |
| 686 |
If an enum name contains an underscore, the CLI parameter **may** instead contain a hyphen, ``-``. |
| 687 |
Leading/Trailing underscores will be stripped. |
| 688 |
|
| 689 |
.. code-block:: python |
| 690 |
|
| 691 |
from cyclopts import App |
| 692 |
from enum import Flag, auto |
| 693 |
|
| 694 |
app = App() |
| 695 |
|
| 696 |
class Permission(Flag): |
| 697 |
READ = auto() |
| 698 |
WRITE = auto() |
| 699 |
EXECUTE = auto() |
| 700 |
|
| 701 |
@app.default |
| 702 |
def default(permissions: Permission = Permission.READ): |
| 703 |
print(f"Permissions: {permissions}") |
| 704 |
|
| 705 |
app() |
| 706 |
|
| 707 |
.. code-block:: console |
| 708 |
|
| 709 |
$ my-program |
| 710 |
Permissions: Permission.READ |
| 711 |
|
| 712 |
$ my-program write |
| 713 |
Permissions: Permission.WRITE |
| 714 |
|
| 715 |
$ my-program read write |
| 716 |
Permissions: Permission.READ|WRITE |
| 717 |
|
| 718 |
$ my-program --permissions.write |
| 719 |
Permissions: Permission.WRITE |
| 720 |
|
| 721 |
$ my-program --permissions.write --permissions.read |
| 722 |
Permissions: Permission.READ|WRITE |
| 723 |
|
| 724 |
.. note:: |
| 725 |
If you want to directly expose the flags as booleans (e.g. ``--read``), then see :ref:`Namespace Flattening <Namespace Flattening>`. |
| 726 |
|
| 727 |
|
| 728 |
.. _Coercion Rules - Dataclasses: |
| 729 |
|
| 730 |
******** |
| 731 |
date |
| 732 |
******** |
| 733 |
|
| 734 |
Cyclopts supports parsing dates into a :class:`~datetime.date` object. It uses :meth:`~datetime.date.fromisoformat` under the hood, so the only supported format is ``%Y-%m-%d`` (e.g. 1956-01-31). |
| 735 |
However, if you use newer Python (>= 3.11), it also supports other formats such as ``%Y%m%d`` (e.g., 20191204), 2021-W01-1, etc, defined by ISO 8601. |
| 736 |
|
| 737 |
|
| 738 |
******** |
| 739 |
datetime |
| 740 |
******** |
| 741 |
|
| 742 |
Cyclopts supports parsing timestamps into a :class:`~datetime.datetime` object. The supplied time must be in one of the following formats: |
| 743 |
|
| 744 |
- ``%Y-%m-%d`` (e.g. 1956-01-31) |
| 745 |
- ``%Y-%m-%dT%H:%M:%S`` (e.g. 1956-01-31T10:00:00) |
| 746 |
- ``%Y-%m-%d %H:%M:%S`` (e.g. 1956-01-31 10:00:00) |
| 747 |
- ``%Y-%m-%dT%H:%M:%S%z`` (e.g. 1956-01-31T10:00:00+0000) |
| 748 |
- ``%Y-%m-%dT%H:%M:%S.%f`` (e.g. 1956-01-31T10:00:00.123456) |
| 749 |
- ``%Y-%m-%dT%H:%M:%S.%f%z`` (e.g. 1956-01-31T10:00:00.123456+0000) |
| 750 |
|
| 751 |
|
| 752 |
********* |
| 753 |
timedelta |
| 754 |
********* |
| 755 |
Cyclopts supports parsing time durations into a :class:`~datetime.timedelta` object. The supplied time must be in one of the following formats: |
| 756 |
|
| 757 |
- ``30s`` - 30 seconds |
| 758 |
- ``5m`` - 5 minutes |
| 759 |
- ``2h`` - 2 hours |
| 760 |
- ``1d`` - 1 day |
| 761 |
- ``3w`` - 3 weeks |
| 762 |
- ``6M`` - 6 months (approximate) |
| 763 |
- ``1y`` - 1 year (approximate) |
| 764 |
|
| 765 |
Combining durations is also supported: |
| 766 |
|
| 767 |
- "1h30m" - 1 hour and 30 minutes |
| 768 |
- "1d12h" - 1 day and 12 hours |
| 769 |
|
| 770 |
******************** |
| 771 |
User-Defined Classes |
| 772 |
******************** |
| 773 |
Cyclopts supports classically defined user classes, as well as classes defined by the following dataclass-like libraries: |
| 774 |
|
| 775 |
* `attrs <https://www.attrs.org/en/stable/>`_ |
| 776 |
* `dataclass <https://docs.python.org/3/library/dataclasses.html>`_ |
| 777 |
* `NamedTuple <https://docs.python.org/3/library/typing.html#typing.NamedTuple>`_ |
| 778 |
* `pydantic <https://docs.pydantic.dev/latest/>`_ |
| 779 |
* `TypedDict <https://docs.python.org/3/library/typing.html#typing.TypedDict>`_ |
| 780 |
|
| 781 |
.. note:: |
| 782 |
For ``pydantic`` classes, Cyclopts will *not* internally perform type conversions and instead relies on pydantic's coercion engine. |
| 783 |
|
| 784 |
Subkey parsing allows for assigning values positionally and by keyword with a dot-separator. |
| 785 |
|
| 786 |
.. code-block:: python |
| 787 |
|
| 788 |
from cyclopts import App |
| 789 |
from dataclasses import dataclass |
| 790 |
from typing import Literal |
| 791 |
|
| 792 |
app = App() |
| 793 |
|
| 794 |
@dataclass |
| 795 |
class User: |
| 796 |
name: str |
| 797 |
age: int |
| 798 |
region: Literal["us", "ca"] = "us" |
| 799 |
|
| 800 |
@app.default |
| 801 |
def main(user: User): |
| 802 |
print(user) |
| 803 |
|
| 804 |
app() |
| 805 |
|
| 806 |
.. code-block:: console |
| 807 |
|
| 808 |
$ my-program --help |
| 809 |
Usage: main COMMAND [ARGS] [OPTIONS] |
| 810 |
|
| 811 |
╭─ Commands ──────────────────────────────────────────────────────────────────────╮ |
| 812 |
│ --help -h Display this message and exit. │ |
| 813 |
│ --version Display application version. │ |
| 814 |
╰─────────────────────────────────────────────────────────────────────────────────╯ |
| 815 |
╭─ Parameters ────────────────────────────────────────────────────────────────────╮ |
| 816 |
│ * USER.NAME --user.name [required] │ |
| 817 |
│ * USER.AGE --user.age [required] │ |
| 818 |
│ USER.REGION --user.region [choices: us, ca] [default: us] │ |
| 819 |
╰─────────────────────────────────────────────────────────────────────────────────╯ |
| 820 |
|
| 821 |
$ my-program 'Bob Smith' 30 |
| 822 |
User(name='Bob Smith', age=30, region='us') |
| 823 |
|
| 824 |
$ my-program --user.name 'Bob Smith' --user.age 30 |
| 825 |
User(name='Bob Smith', age=30, region='us') |
| 826 |
|
| 827 |
$ my-program --user.name 'Bob Smith' 30 --user.region=ca |
| 828 |
User(name='Bob Smith', age=30, region='ca') |
| 829 |
|
| 830 |
|
| 831 |
Cyclopts will recursively search for :class:`~.Parameter` annotations and respect them: |
| 832 |
|
| 833 |
.. code-block:: python |
| 834 |
|
| 835 |
from cyclopts import App, Parameter |
| 836 |
from dataclasses import dataclass |
| 837 |
from typing import Annotated |
| 838 |
|
| 839 |
app = App() |
| 840 |
|
| 841 |
@dataclass |
| 842 |
class User: |
| 843 |
# Beginning with "--" will completely override the parenting parameter name. |
| 844 |
name: Annotated[str, Parameter(name="--nickname")] |
| 845 |
# Not beginning with "--" will tack it on to the parenting parameter name. |
| 846 |
age: Annotated[int, Parameter(name="years-young")] |
| 847 |
|
| 848 |
@app.default |
| 849 |
def main(user: Annotated[User, Parameter(name="player")]): |
| 850 |
print(user) |
| 851 |
|
| 852 |
app() |
| 853 |
|
| 854 |
.. code-block:: console |
| 855 |
|
| 856 |
$ my-program --help |
| 857 |
Usage: main COMMAND [ARGS] [OPTIONS] |
| 858 |
|
| 859 |
╭─ Commands ────────────────────────────────────────────────╮ |
| 860 |
│ --help -h Display this message and exit. │ |
| 861 |
│ --version Display application version. │ |
| 862 |
╰───────────────────────────────────────────────────────────╯ |
| 863 |
╭─ Parameters ──────────────────────────────────────────────╮ |
| 864 |
│ * NICKNAME --nickname [required] │ |
| 865 |
│ * PLAYER.YEARS-YOUNG [required] │ |
| 866 |
│ --player.years-young │ |
| 867 |
╰───────────────────────────────────────────────────────────╯ |
| 868 |
|
| 869 |
^^^^^^^^^^^^^^^^^^^^ |
| 870 |
Namespace Flattening |
| 871 |
^^^^^^^^^^^^^^^^^^^^ |
| 872 |
The special parameter name ``"*"`` will remove the immediate parameter's name from the dotted-hierarchal name: |
| 873 |
|
| 874 |
.. code-block:: python |
| 875 |
|
| 876 |
from cyclopts import App, Parameter |
| 877 |
from dataclasses import dataclass |
| 878 |
from typing import Annotated |
| 879 |
|
| 880 |
app = App() |
| 881 |
|
| 882 |
@dataclass |
| 883 |
class User: |
| 884 |
name: str |
| 885 |
age: int |
| 886 |
|
| 887 |
@app.default |
| 888 |
def main(user: Annotated[User, Parameter(name="*")]): |
| 889 |
print(user) |
| 890 |
|
| 891 |
app() |
| 892 |
|
| 893 |
.. code-block:: console |
| 894 |
|
| 895 |
$ my-program --help |
| 896 |
Usage: main COMMAND [ARGS] [OPTIONS] |
| 897 |
|
| 898 |
╭─ Commands ─────────────────────────────────────────────╮ |
| 899 |
│ --help -h Display this message and exit. │ |
| 900 |
│ --version Display application version. │ |
| 901 |
╰────────────────────────────────────────────────────────╯ |
| 902 |
╭─ Parameters ───────────────────────────────────────────╮ |
| 903 |
│ * NAME --name [required] │ |
| 904 |
│ * AGE --age [required] │ |
| 905 |
╰────────────────────────────────────────────────────────╯ |
| 906 |
|
| 907 |
This can be used to conveniently share parameters between commands, and to create a global config object. See :ref:`Sharing Parameters`. |
| 908 |
|
| 909 |
^^^^^^^^^^ |
| 910 |
Docstrings |
| 911 |
^^^^^^^^^^ |
| 912 |
Docstrings from the class are used for the help page. Docstrings from the command have priority over class docstrings, if supplied: |
| 913 |
|
| 914 |
.. code-block:: python |
| 915 |
|
| 916 |
from cyclopts import App |
| 917 |
from dataclasses import dataclass |
| 918 |
|
| 919 |
app = App() |
| 920 |
|
| 921 |
@dataclass |
| 922 |
class User: |
| 923 |
name: str |
| 924 |
"First and last name of the user." |
| 925 |
|
| 926 |
age: int |
| 927 |
"Age in years of the user." |
| 928 |
|
| 929 |
@app.default |
| 930 |
def main(user: User): |
| 931 |
"""A short summary of what this program does. |
| 932 |
|
| 933 |
Parameters |
| 934 |
---------- |
| 935 |
user.age: int |
| 936 |
User's age docstring from the command docstring. |
| 937 |
""" |
| 938 |
print(user) |
| 939 |
|
| 940 |
app() |
| 941 |
|
| 942 |
.. code-block:: console |
| 943 |
|
| 944 |
$ my-program --help |
| 945 |
Usage: main COMMAND [ARGS] [OPTIONS] |
| 946 |
|
| 947 |
A short summary of what this program does. |
| 948 |
|
| 949 |
╭─ Commands ──────────────────────────────────────────────────────────────────────╮ |
| 950 |
│ --help -h Display this message and exit. │ |
| 951 |
│ --version Display application version. │ |
| 952 |
╰─────────────────────────────────────────────────────────────────────────────────╯ |
| 953 |
╭─ Parameters ────────────────────────────────────────────────────────────────────╮ |
| 954 |
│ * USER.NAME --user.name First and last name of the user. [required] │ |
| 955 |
│ * USER.AGE --user.age User's age docstring from the command docstring. │ |
| 956 |
│ [required] │ |
| 957 |
╰─────────────────────────────────────────────────────────────────────────────────╯ |
| 958 |
|
| 959 |
|
| 960 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 961 |
Parameter(accepts_keys=False) |
| 962 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 963 |
If the class is annotated with ``Parameter(accepts_keys=False)``, then no dot-notation subkeys are exported. |
| 964 |
The class parameter will consume enough tokens to populate the **required positional** arguments. |
| 965 |
|
| 966 |
.. code-block:: python |
| 967 |
|
| 968 |
from cyclopts import App, Parameter |
| 969 |
from dataclasses import dataclass |
| 970 |
from typing import Annotated, Literal |
| 971 |
|
| 972 |
app = App() |
| 973 |
|
| 974 |
@dataclass |
| 975 |
class User: |
| 976 |
name: str |
| 977 |
age: int |
| 978 |
region: Literal["us", "ca"] = "us" |
| 979 |
|
| 980 |
@app.default |
| 981 |
def main(user: Annotated[User, Parameter(accepts_keys=False)]): |
| 982 |
print(user) |
| 983 |
|
| 984 |
app() |
| 985 |
|
| 986 |
.. code-block:: console |
| 987 |
|
| 988 |
$ my-program --help |
| 989 |
Usage: main COMMAND [ARGS] [OPTIONS] |
| 990 |
|
| 991 |
╭─ Commands ─────────────────────────────────────────────────────────────────────╮ |
| 992 |
│ --help -h Display this message and exit. │ |
| 993 |
│ --version Display application version. │ |
| 994 |
╰────────────────────────────────────────────────────────────────────────────────╯ |
| 995 |
╭─ Parameters ───────────────────────────────────────────────────────────────────╮ |
| 996 |
│ * USER --user [required] │ |
| 997 |
╰────────────────────────────────────────────────────────────────────────────────╯ |
| 998 |
|
| 999 |
$ my-program 'Bob Smith' 27 |
| 1000 |
User(name='Bob Smith', age=27, region='us') |
| 1001 |
|
| 1002 |
$ my-program 'Bob Smith' |
| 1003 |
╭─ Error ────────────────────────────────────────────────────────────────────────╮ |
| 1004 |
│ Parameter --user requires 2 arguments. Only got 1. │ |
| 1005 |
╰────────────────────────────────────────────────────────────────────────────────╯ |
| 1006 |
|
| 1007 |
In this example, we are unable to change the ``region`` parameter of ``User`` from the CLI. |
| 1008 |
|
| 1009 |
|
| 1010 |
.. _Typer: https://typer.tiangolo.com |