Debian Codegraph @

docs/source/api.rst

raw
1 .. _API:
2
3 ===
4 API
5 ===
6
7 .. autoclass:: cyclopts.App
8 :members: default, command, version_print, help_print, interactive_shell, parse_commands, parse_known_args, parse_args, run_async, assemble_argument_collection, update, generate_docs, generate_completion, install_completion, register_install_completion_command
9 :special-members: __call__, __getitem__, __iter__
10
11 Cyclopts Application.
12
13 .. attribute:: name
14 :type: Optional[Union[str, Iterable[str]]]
15 :value: None
16
17 Name of application, or subcommand if registering to another application. Name resolution order:
18
19 1. User specified :attr:`~.App.name` parameter.
20 2. If a :attr:`~.App.default` function has been registered, the name of that function.
21 3. If the module name is ``__main__.py``, the name of the encompassing package.
22 4. The value of :data:`sys.argv[0] <sys.argv>`; i.e. the name of the python script.
23
24 Multiple names can be provided in the case of a subcommand, but this is relatively unusual.
25
26 Special value ``"*"`` can be used when registering sub-apps with :meth:`~.App.command` to flatten all commands from the sub-app into the parent app. See :ref:`Flattening SubCommands` for details.
27
28 Example:
29
30 .. code-block:: python
31
32 from cyclopts import App
33
34 app = App()
35 app.command(App(name="foo"))
36
37 @app["foo"].command
38 def bar():
39 print("Running bar.")
40
41 app()
42
43 .. code-block:: console
44
45 $ my-script foo bar
46 Running bar.
47
48 .. attribute:: alias
49 :type: Optional[Union[str, Iterable[str]]]
50 :value: None
51
52 Extends :attr:`.name` with additional names.
53 Unlike :attr:`.name`, this does not override Cyclopts-derived names.
54
55 .. code-block:: python
56
57 from cyclopts import App
58
59 app = App()
60
61 @app.command(alias="bar")
62 def foo():
63 print("Running foo.")
64
65 app()
66
67 .. code-block:: console
68
69 $ my-script foo
70 Running bar.
71
72 $ my-script bar
73 Running bar.
74
75 .. attribute:: synonym
76 :type: Optional[Union[str, Iterable[str]]]
77 :value: None
78
79 Alternate names that trigger a "Did you mean..." suggestion when typed, but do **not**
80 register the command under those names.
81
82 Unlike :attr:`.alias`, synonyms are not runnable and are hidden from ``--help``.
83 They exist to guide users who type a semantically equivalent but orthographically
84 dissimilar token that Cyclopts' fuzzy matcher would otherwise miss (e.g., ``remove``
85 when the command is ``uninstall``).
86
87 .. code-block:: python
88
89 from cyclopts import App
90
91 app = App()
92
93 @app.command(synonym=["remove", "rm"])
94 def uninstall(name: str):
95 print(f"uninstalling {name}")
96
97 app()
98
99 .. code-block:: console
100
101 $ my-script uninstall mypackage
102 uninstalling mypackage
103
104 $ my-script remove mypackage
105 Unknown command "remove". Did you mean "uninstall"? Available commands: uninstall.
106
107 See :ref:`Synonyms` for details.
108
109 .. attribute:: help
110 :type: Optional[str]
111 :value: None
112
113 Text to display on help screen.
114 If not supplied, fallbacks to parsing the docstring of function registered with :meth:`.App.default`.
115
116 .. code-block:: python
117
118 from cyclopts import App
119
120 app = App(help="This is my help string.")
121 app()
122
123 .. code-block:: console
124
125 $ my-script --help
126 Usage: scratch.py COMMAND
127
128 This is my help string.
129
130 ╭─ Commands ────────────────────────────────────────────────────────────╮
131 │ --help -h Display this message and exit. │
132 │ --version Display application version. │
133 ╰───────────────────────────────────────────────────────────────────────╯
134
135 .. attribute:: help_flags
136 :type: Union[str, Iterable[str]]
137 :value: ("--help", "-h")
138
139 CLI flags that trigger :meth:`help_print`.
140 Set to an empty list to disable this feature.
141 Defaults to ``["--help", "-h"]``.
142
143 .. attribute:: help_format
144 :type: Optional[Literal["plaintext", "markdown", "md", "restructuredtext", "rst"]]
145 :value: None
146
147 The markup language used in function docstring.
148 If :obj:`None`, fallback to parenting :attr:`~.App.help_format`.
149 If no :attr:`~.App.help_format` is defined, falls back to ``"markdown"``.
150
151 .. attribute:: help_formatter
152 :type: Union[None, Literal["default", "plain"], HelpFormatter]
153 :value: None
154
155 Help formatter to use for rendering help panels.
156
157 * If :obj:`None` (default), inherits from parent :class:`.App`, eventually defaulting to :class:`~cyclopts.help.DefaultFormatter`.
158
159 * If ``"default"``, uses :class:`~cyclopts.help.DefaultFormatter`.
160
161 * If ``"plain"``, uses :class:`~cyclopts.help.PlainFormatter` for no-frills plain text output.
162
163 * If a callable (see :class:`~cyclopts.help.protocols.HelpFormatter` protocol), uses the provided formatter.
164
165 Example:
166
167 .. code-block:: python
168
169 from cyclopts import App
170 from cyclopts.help import DefaultFormatter, PlainFormatter, PanelSpec
171
172 # Use plain text formatter
173 app = App(help_formatter="plain")
174
175 # Use default formatter with customization
176 app = App(help_formatter=DefaultFormatter(
177 panel_spec=PanelSpec(border_style="blue")
178 ))
179
180 See :ref:`Help Customization` for detailed examples and advanced usage.
181
182 .. attribute:: help_prologue
183 :type: Optional[str]
184 :value: None
185
186 Text to display at the beginning of the help screen, before the usage section.
187 If :obj:`None`, no prologue is displayed.
188 If not set, attempts to inherit from parenting :class:`.App`.
189
190 The prologue supports the same formatting as :attr:`help` based on :attr:`help_format` (markdown, plaintext, restructuredtext, or rich).
191
192 Example:
193
194 .. code-block:: python
195
196 from cyclopts import App
197
198 app = App(
199 name="myapp",
200 help="My application help.",
201 help_prologue=f"myapp, v1.0.0 (http://example.myapp.com)"
202 )
203 app()
204
205 .. code-block:: console
206
207 $ my-script --help
208 myapp, v1.0.0 (http://example.myapp.com)
209
210 Usage: myapp COMMAND
211
212 My application help.
213
214 ╭─ Commands ────────────────────────────────────────────────────────────╮
215 │ --help -h Display this message and exit. │
216 │ --version Display application version. │
217 ╰───────────────────────────────────────────────────────────────────────╯
218
219 .. attribute:: help_epilogue
220 :type: Optional[str]
221 :value: None
222
223 Text to display at the end of the help screen, after all help panels.
224 Commonly used for version information, contact details, or additional notes.
225 If :obj:`None`, no epilogue is displayed.
226 If not set, attempts to inherit from parenting :class:`.App`.
227
228 The epilogue supports the same formatting as :attr:`help` based on :attr:`help_format` (markdown, plaintext, restructuredtext, or rich).
229
230 Example:
231
232 .. code-block:: python
233
234 from cyclopts import App
235
236 app = App(
237 name="myapp",
238 help="My application help.",
239 help_epilogue="Support: [email protected]"
240 )
241 app()
242
243 .. code-block:: console
244
245 $ my-script --help
246 Usage: myapp COMMAND
247
248 My application help.
249
250 ╭─ Commands ────────────────────────────────────────────────────────────╮
251 │ --help -h Display this message and exit. │
252 │ --version Display application version. │
253 ╰───────────────────────────────────────────────────────────────────────╯
254
255 Support: [email protected]
256
257 .. attribute:: help_on_error
258 :type: Optional[bool]
259 :value: None
260
261 Prints the help-page before printing an error.
262 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to :obj:`False`.
263
264 .. attribute:: print_error
265 :type: Optional[bool]
266 :value: None
267
268 Print a rich-formatted error on error.
269 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to :obj:`True`.
270
271 .. attribute:: exit_on_error
272 :type: Optional[bool]
273 :value: None
274
275 If there is an error parsing the CLI tokens, invoke :func:`sys.exit(1) <sys.exit>`.
276 Otherwise, continue to raise the exception.
277 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to :obj:`True`.
278
279 .. attribute:: verbose
280 :type: Optional[bool]
281 :value: None
282
283 Populate exception strings with more information intended for developers.
284 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to :obj:`False`.
285
286 .. attribute:: error_formatter
287 :type: Optional[Callable[[CycloptsError], Any]]
288 :value: None
289
290 A callable that formats :exc:`.CycloptsError` exceptions for display.
291 The callable receives the exception and should return any Rich-printable object (string, :class:`~rich.text.Text`, :class:`~rich.panel.Panel`, etc.).
292 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to :func:`.CycloptsPanel`.
293
294 See :ref:`Custom Error Formatting` for examples.
295
296 .. attribute:: version_format
297 :type: Optional[Literal["plaintext", "markdown", "md", "restructuredtext", "rst"]]
298 :value: None
299
300 The markup language used in the version string.
301 If :obj:`None`, fallback to parenting :attr:`~.App.version_format`.
302 If no :attr:`~.App.version_format` is defined, falls back to resolved :attr:`~.App.help_format`.
303
304 .. attribute:: usage
305 :type: Optional[str]
306 :value: None
307
308 Text to be displayed in lieue of the default ``Usage: app COMMAND ...`` at the beginning of the help-page.
309 Set to an empty-string ``""`` to disable showing the default usage.
310
311 .. attribute:: show
312 :type: bool
313 :value: True
314
315 Show this **command** on the help screen.
316 Hidden commands (``show=False``) are still executable.
317
318 .. code-block:: python
319
320 from cyclopts import App
321 app = App()
322
323 @app.command
324 def foo():
325 print("Running foo.")
326
327 @app.command(show=False)
328 def bar():
329 print("Running bar.")
330
331 app()
332
333 .. code-block:: console
334
335 $ my-script foo
336 Running foo.
337
338 $ my-script bar
339 Running bar.
340
341 $ my-script --help
342 Usage: scratch.py COMMAND
343
344 ╭─ Commands ─────────────────────────────────────────────────╮
345 │ foo │
346 │ --help -h Display this message and exit. │
347 │ --version Display application version. │
348 ╰────────────────────────────────────────────────────────────╯
349
350 .. attribute:: sort_key
351 :type: Any
352 :value: None
353
354 Modifies command display order on the help-page.
355
356 1. If :attr:`sort_key` is a generator, it will be consumed immediately with :func:`next` to get the actual value.
357
358 2. If :attr:`sort_key`, or any of it's contents, are ``Callable``, then invoke it ``sort_key(app)`` and apply the returned value to (3) if :obj:`None`, (4) otherwise.
359
360 3. For all commands with ``sort_key==None`` (default value), sort them alphabetically.
361 These sorted commands will be displayed **after** ``sort_key != None`` list (see 4).
362
363 4. For all commands with ``sort_key!=None``, sort them by ``(sort_key, app.name)``.
364 It is the user's responsibility that ``sort_key`` s are comparable.
365
366 Example usage:
367
368 .. code-block:: python
369
370 from cyclopts import App
371
372 app = App()
373
374 @app.command # sort_key not specified; will be sorted AFTER bob/charlie.
375 def alice():
376 """Alice help description."""
377
378 @app.command(sort_key=2)
379 def bob():
380 """Bob help description."""
381
382 @app.command(sort_key=1)
383 def charlie():
384 """Charlie help description."""
385
386 app()
387
388 Resulting help-page:
389
390 .. code-block:: text
391
392 Usage: demo.py COMMAND
393
394 ╭─ Commands ──────────────────────────────────────────────────╮
395 │ charlie Charlie help description. │
396 │ bob Bob help description. │
397 │ alice Alice help description. │
398 │ --help -h Display this message and exit. │
399 │ --version Display application version. │
400 ╰─────────────────────────────────────────────────────────────╯
401
402 Using generators (e.g., :func:`itertools.count`):
403
404 .. code-block:: python
405
406 import itertools
407 from cyclopts import App
408
409 app = App()
410 counter = itertools.count()
411
412 @app.command(sort_key=counter)
413 def beta():
414 """Beta help description."""
415
416 @app.command(sort_key=counter)
417 def alpha():
418 """Alpha help description."""
419
420 app()
421
422 .. code-block:: text
423
424 Usage: demo.py COMMAND
425
426 ╭─ Commands ──────────────────────────────────────────────────╮
427 │ beta Beta help description. │
428 │ alpha Alpha help description. │
429 │ --help -h Display this message and exit. │
430 │ --version Display application version. │
431 ╰─────────────────────────────────────────────────────────────╯
432
433 .. attribute:: version
434 :type: Union[None, str, Callable]
435 :value: None
436
437 Version to be displayed when a :attr:`version_flags` is parsed.
438 Defaults to the version of the package instantiating :class:`.App`.
439 If a :obj:`~typing.Callable`, it will be invoked with no arguments when version is queried.
440
441 .. attribute:: version_flags
442 :type: Union[str, Iterable[str]]
443 :value: ("--version",)
444
445 Token(s) that trigger :meth:`version_print`.
446 Set to an empty list to disable version feature.
447 Defaults to ``["--version"]``.
448
449 .. attribute:: console
450 :type: ~rich.console.Console
451 :value: None
452
453 Default :class:`~rich.console.Console` to use when displaying runtime messages.
454 Cyclopts console resolution is as follows:
455
456 #. Any explicitly passed in console to methods like :meth:`.App.__call__`, :meth:`.App.parse_args`, etc.
457 #. The relevant subcommand's :attr:`.App.console` attribute, if not :obj:`None`.
458 #. The parenting :attr:`.App.console` (and so on), if not :obj:`None`.
459 #. If all values are :obj:`None`, then the default :class:`~rich.console.Console` is used.
460
461 .. attribute:: error_console
462 :type: ~rich.console.Console
463 :value: None
464
465 Default :class:`~rich.console.Console` to use when displaying error messages.
466 Cyclopts error_console resolution is as follows:
467
468 #. Any explicitly passed in error_console to methods like :meth:`.App.__call__`, :meth:`.App.parse_args`, etc.
469 #. The relevant subcommand's :attr:`.App.error_console` attribute, if not :obj:`None`.
470 #. The parenting :attr:`.App.error_console` (and so on), if not :obj:`None`.
471 #. If all values are :obj:`None`, then a default :class:`~rich.console.Console` with ``stderr=True`` is used.
472
473 This separation of error output from normal output follows Unix conventions, allowing
474 users to redirect error messages independently from normal output (e.g., ``program > output.txt 2> errors.txt``).
475
476 .. attribute:: default_parameter
477 :type: Parameter
478 :value: None
479
480 Default :class:`.Parameter` configuration. Unspecified values of command-annotated :class:`.Parameter` will inherit these values.
481 See :ref:`Default Parameter` for more details.
482
483 .. attribute:: group
484 :type: Union[None, str, Group, Iterable[Union[str, Group]]]
485 :value: None
486
487 The group(s) that :attr:`default_command` belongs to.
488
489 * If :obj:`None`, defaults to the ``"Commands"`` group.
490
491 * If :obj:`str`, use an existing :class:`.Group` (from neighboring sub-commands) with name,
492 **or** create a :class:`.Group` with provided name if it does not exist.
493
494 * If :class:`.Group`, directly use it.
495
496 .. attribute:: group_commands
497 :type: Group
498 :value: Group("Commands")
499
500 The default :class:`.Group` that sub-commands are assigned to.
501
502 .. attribute:: group_arguments
503 :type: Group
504 :value: Group("Arguments")
505
506 The default :class:`.Group` that positional-only parameters are assigned to.
507
508 .. attribute:: group_parameters
509 :type: Group
510 :value: Group("Parameters")
511
512 The default :class:`.Group` that non-positional-only parameters are assigned to.
513
514 .. attribute:: validator
515 :type: Union[None, Callable, list[Callable]]
516 :value: []
517
518 A function (or list of functions) where all the converted CLI-provided variables will be **keyword-unpacked**,
519 regardless of their positional/keyword-type in the command function signature.
520 The python variable names will be used, which may differ from their CLI names.
521
522 Example usage:
523
524 .. code-block:: python
525
526 def validator(**kwargs):
527 "Raise an exception if something is invalid."
528
529 This validator runs **after** :class:`.Parameter` and :class:`.Group` validators.
530
531 .. attribute:: name_transform
532 :type: Optional[Callable[[str], str]]
533 :value: None
534
535 A function that converts function names to their CLI command counterparts.
536
537 The function must have signature:
538
539 .. code-block:: python
540
541 def name_transform(s: str) -> str:
542 ...
543
544 The returned string should be **without** a leading ``--``.
545 If :obj:`None` (default value), uses :func:`~.default_name_transform`.
546 Subapps inherit from the first non-:obj:`None` parent :attr:`name_transform`.
547
548 .. attribute:: config
549 :type: Union[None, Callable, Iterable[Callable]]
550 :value: None
551
552 A function or list of functions that are consecutively executed after parsing CLI tokens and environment variables.
553 These function(s) are called **before** any conversion and validation.
554 Each config function must have signature:
555
556 .. code-block:: python
557
558 def config(app: "App", commands: Tuple[str, ...], arguments: ArgumentCollection):
559 """Modifies given mapping inplace with some injected values.
560
561 Parameters
562 ----------
563 app: App
564 The current command app being executed.
565 commands: Tuple[str, ...]
566 The CLI strings that led to the current command function.
567 arguments: ArgumentCollection
568 Complete ArgumentCollection for the app.
569 Modify this collection inplace to influence values provided to the function.
570 """
571
572 The intended use-case of this feature is to allow users to specify functions that can load defaults from some external configuration.
573 See :ref:`cyclopts.config <API Config>` for useful builtins and :ref:`Config Files` for examples.
574
575 .. attribute:: end_of_options_delimiter
576 :type: Optional[str]
577 :value: None
578
579 All tokens after this delimiter will be force-interpreted as positional arguments.
580 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to POSIX-standard ``"--"``.
581 Set to an empty string to disable.
582
583 .. attribute:: suppress_keyboard_interrupt
584 :type: bool
585 :value: True
586
587 If the application receives a keyboard interrupt (Ctrl-C), suppress the error message and exit gracefully.
588 Set to :obj:`False` to let :class:`KeyboardInterrupt` propagate normally.
589
590 .. attribute:: backend
591 :type: Optional[Literal["asyncio", "trio"]]
592 :value: None
593
594 The async backend to use when executing async commands.
595 If not set, attempts to inherit from parenting :class:`.App`, eventually defaulting to ``"asyncio"``.
596
597 Example:
598
599 .. code-block:: python
600
601 from cyclopts import App
602
603 app = App(backend="asyncio")
604
605 @app.default
606 async def main():
607 await some_async_operation()
608
609 app()
610
611 The backend can also be overridden on a per-call basis:
612
613 .. code-block:: python
614
615 app(backend="trio") # Override the app's backend for this call
616
617 .. attribute:: result_action
618 :type: Literal["return_value", "call_if_callable", "print_non_int_return_int_as_exit_code", "print_str_return_int_as_exit_code", "print_str_return_zero", "print_non_none_return_int_as_exit_code", "print_non_none_return_zero", "return_int_as_exit_code_else_zero", "print_non_int_sys_exit", "sys_exit", "return_none", "return_zero", "print_return_zero", "sys_exit_zero", "print_sys_exit_zero"] | Callable[[Any], Any] | Iterable[Literal[...] | Callable[[Any], Any]] | None
619 :value: None
620
621 Controls how :meth:`.App.__call__` and :meth:`.App.run_async` handle command return values. By default (``"print_non_int_sys_exit"``), the app will call :func:`sys.exit` with an appropriate exit code. This default was chosen for consistent functionality between standalone scripts, and console entrypoints.
622
623 Can be a predefined literal string, a custom callable that takes the result and returns a processed value, or a **sequence of actions** to be applied left-to-right in a pipeline.
624
625 Each predefined mode's exact behavior is shown below:
626
627 **"print_non_int_sys_exit"** (default)
628
629 The default CLI mode. Prints non-int values to stdout, then calls :func:`sys.exit` with the appropriate exit code.
630
631 .. code-block:: python
632
633 if isinstance(result, bool):
634 sys.exit(0 if result else 1) # i.e. True is success
635 elif isinstance(result, int):
636 sys.exit(result)
637 elif result is not None:
638 print(result)
639 sys.exit(resolve_returncode(result))
640 else:
641 sys.exit(resolve_returncode(result))
642
643 See :ref:`Custom Return Code Protocol <custom-return-code-protocol>` for :func:`~cyclopts.resolve_returncode`.
644
645 **"return_value"**
646
647 Returns the command's value unchanged. Use for embedding Cyclopts in other Python code or testing.
648
649 .. code-block:: python
650
651 return result
652
653 **"call_if_callable"**
654
655 Calls the result if it's callable (with no arguments), otherwise returns it unchanged. Useful for the dataclass command pattern where commands return class instances with ``__call__`` methods. Intended to be used in composition with other result actions (e.g., ``["call_if_callable", "print_non_int_sys_exit"]``).
656
657 .. code-block:: python
658
659 return result() if callable(result) else result
660
661 See :ref:`Dataclass Commands` for usage examples.
662
663 **"sys_exit"**
664
665 Never prints output. Calls :func:`sys.exit` with the appropriate exit code. Useful for CLI apps that handle their own output and just need exit code handling.
666
667 .. code-block:: python
668
669 if isinstance(result, bool):
670 sys.exit(0 if result else 1) # i.e. True is success
671 elif isinstance(result, int):
672 sys.exit(result)
673 else:
674 sys.exit(resolve_returncode(result))
675
676 **"print_non_int_return_int_as_exit_code"**
677
678 Prints non-int values, returns int/bool as exit codes. Useful for testing and embedding.
679
680 .. code-block:: python
681
682 if isinstance(result, bool):
683 return 0 if result else 1 # i.e. True is success
684 elif isinstance(result, int):
685 return result
686 elif result is not None:
687 print(result)
688 return resolve_returncode(result)
689 else:
690 return resolve_returncode(result)
691
692 **"print_str_return_int_as_exit_code"**
693
694 Only prints string return values. Returns int/bool as exit codes, silently returns 0 for other types.
695
696 .. code-block:: python
697
698 if isinstance(result, str):
699 print(result)
700 return resolve_returncode(result)
701 elif isinstance(result, bool):
702 return 0 if result else 1 # i.e. True is success
703 elif isinstance(result, int):
704 return result
705 else:
706 return resolve_returncode(result)
707
708 **"print_str_return_zero"**
709
710 Only prints string return values, always returns 0. Useful for simple output-only CLIs.
711
712 .. code-block:: python
713
714 if isinstance(result, str):
715 print(result)
716 return resolve_returncode(result)
717
718 **"print_non_none_return_int_as_exit_code"**
719
720 Prints all non-None values (including ints), returns int/bool as exit codes.
721
722 .. code-block:: python
723
724 if result is not None:
725 print(result)
726 if isinstance(result, bool):
727 return 0 if result else 1 # i.e. True is success
728 elif isinstance(result, int):
729 return result
730 return resolve_returncode(result)
731
732 **"print_non_none_return_zero"**
733
734 Prints all non-None values (including ints), always returns 0.
735
736 .. code-block:: python
737
738 if result is not None:
739 print(result)
740 return resolve_returncode(result)
741
742 **"return_int_as_exit_code_else_zero"**
743
744 Never prints output. Returns int/bool as exit codes, 0 for all other types. Useful for silent CLIs.
745
746 .. code-block:: python
747
748 if isinstance(result, bool):
749 return 0 if result else 1 # i.e. True is success
750 elif isinstance(result, int):
751 return result
752 else:
753 return resolve_returncode(result)
754
755 **"return_none"**
756
757 Always returns None, regardless of the command's return value.
758
759 .. code-block:: python
760
761 return None
762
763 **"return_zero"**
764
765 Always returns 0, regardless of the command's return value.
766
767 .. code-block:: python
768
769 return resolve_returncode(result)
770
771 **"print_return_zero"**
772
773 Always prints the result (even None), then always returns 0.
774
775 .. code-block:: python
776
777 print(result)
778 return resolve_returncode(result)
779
780 **"sys_exit_zero"**
781
782 Always calls :func:`sys.exit(0) <sys.exit>`, regardless of the command's return value.
783
784 .. code-block:: python
785
786 sys.exit(resolve_returncode(result))
787
788 **"print_sys_exit_zero"**
789
790 Always prints the result (even None), then calls :func:`sys.exit(0) <sys.exit>`.
791
792 .. code-block:: python
793
794 print(result)
795 sys.exit(resolve_returncode(result))
796
797 **Custom Callable**
798
799 Provide a function for fully custom result handling. Receives the command's return value and returns a processed value.
800
801 .. code-block:: python
802
803 def custom_handler(result):
804 if result is None:
805 return 0
806 elif isinstance(result, str):
807 print(f"[OUTPUT] {result}")
808 return 0
809 return result
810
811 app = App(result_action=custom_handler)
812
813 **Sequence of Actions**
814
815 Provide a sequence (list or tuple) of actions to create a result-processing pipeline. Actions are applied left-to-right, with each action receiving the result of the previous action.
816
817 .. code-block:: python
818
819 def uppercase(result):
820 return result.upper() if isinstance(result, str) else result
821
822 def add_prefix(result):
823 return f"[OUTPUT] {result}" if isinstance(result, str) else result
824
825 # Pipeline: result → uppercase → add_prefix → return
826 app = App(result_action=[uppercase, add_prefix, "return_value"])
827
828 @app.command
829 def greet(name: str) -> str:
830 return f"hello {name}"
831
832 result = app(["greet", "world"])
833 # result == "[OUTPUT] HELLO WORLD"
834
835 Actions in a sequence can be any combination of predefined literal strings and custom callables. Empty sequences raise a ``ValueError`` at app initialization.
836
837 Example:
838
839 .. code-block:: python
840
841 from cyclopts import App
842
843 # For CLI applications with console_scripts entry points
844 app = App(result_action="print_non_int_return_int_as_exit_code")
845
846 @app.command
847 def greet(name: str) -> str:
848 return f"Hello {name}!"
849
850 app()
851
852 See :ref:`Result Action` for detailed examples and usage patterns.
853
854 .. autoclass:: cyclopts.Parameter
855 :special-members: __call__
856
857 .. attribute:: name
858 :type: Union[None, str, Iterable[str]]
859 :value: None
860
861 Name(s) to expose to the CLI.
862 If not specified, cyclopts will apply :attr:`name_transform` to the python parameter name.
863
864 .. code-block:: python
865
866 from cyclopts import App, Parameter
867 from typing import Annotated
868
869 app = App()
870
871 @app.default
872 def main(foo: Annotated[int, Parameter(name=("bar", "-b"))]):
873 print(f"{foo=}")
874
875 app()
876
877 .. code-block:: console
878
879 $ my-script --help
880 Usage: main COMMAND [ARGS] [OPTIONS]
881
882 ╭─ Commands ─────────────────────────────────────────────────────╮
883 │ --help -h Display this message and exit. │
884 │ --version Display application version. │
885 ╰────────────────────────────────────────────────────────────────╯
886 ╭─ Parameters ───────────────────────────────────────────────────╮
887 │ * BAR --bar -b [required] │
888 ╰────────────────────────────────────────────────────────────────╯
889
890 $ my-script --bar 100
891 foo=100
892
893 $ my-script -b 100
894 foo=100
895
896 If specifying name in a nested data structure (e.g. a dataclass), beginning the name with a hyphen ``-`` will override any hierarchical dot-notation.
897
898 .. code-block:: python
899
900 from cyclopts import App, Parameter
901 from dataclasses import dataclass
902 from typing import Annotated
903
904 app = App()
905
906 @dataclass
907 class User:
908 id: int # default behavior
909 email: Annotated[str, Parameter(name="--email")] # overrides
910 pwd: Annotated[str, Parameter(name="password")] # dot-notation with parent
911
912 @app.command
913 def create(user: User):
914 print(f"Creating {user=}")
915
916 app()
917
918 .. code-block:: console
919
920 $ my-script create --help
921 Usage: scratch.py create [ARGS] [OPTIONS]
922
923 ╭─ Parameters ───────────────────────────────────────────────────╮
924 │ * USER.ID --user.id [required] │
925 │ * EMAIL --email [required] │
926 │ * USER.PASSWORD [required] │
927 │ --user.password │
928 ╰────────────────────────────────────────────────────────────────╯
929
930 .. attribute:: alias
931 :type: Union[None, str, Iterable[str]]
932 :value: None
933
934 Additional name(s) to expose to the CLI.
935 Unlike :attr:`.name`, this does not override Cyclopts-derived names.
936
937 The following two examples are functionally equivalent:
938
939 .. code-block:: python
940
941 @app.default
942 def main(foo: Annotated[int, Parameter(name=["--foo", "-f"])]):
943 pass
944
945 .. code-block:: python
946
947 @app.default
948 def main(foo: Annotated[int, Parameter(alias="-f")]):
949 pass
950
951 .. attribute:: converter
952 :type: Optional[Callable]
953 :value: None
954
955 A function that converts tokens into an object. The converter should have signature:
956
957 .. code-block:: python
958
959 def converter(type_, tokens) -> Any:
960 pass
961
962 Where ``type_`` is the parameter's type hint, and ``tokens`` is either:
963
964 * A ``list[cyclopts.Token]`` of CLI tokens (most commonly).
965
966 .. code-block:: python
967
968 from cyclopts import App, Parameter
969 from typing import Annotated
970
971 app = App()
972
973 def converter(type_, tokens):
974 assert type_ == tuple[int, int]
975 return tuple(2 * int(x.value) for x in tokens)
976
977 @app.default
978 def main(coordinates: Annotated[tuple[int, int], Parameter(converter=converter)]):
979 print(f"{coordinates=}")
980
981 app()
982
983 .. code-block:: console
984
985 $ python my-script.py 7 12
986 coordinates=(14, 24)
987
988 * A ``dict`` of :class:`.Token` if keys are specified in the CLI. E.g.
989
990 .. code-block:: console
991
992 $ python my-script.py --foo.key1=val1
993
994 would be parsed into:
995
996 .. code-block:: python
997
998 tokens = {
999 "key1": ["val1"],
1000 }
1001
1002 If not provided, defaults to Cyclopts's internal coercion engine.
1003 If a pydantic type-hint is provided, Cyclopts will disable its internal coercion
1004 engine (including this `converter` argument) and leave the coercion to pydantic.
1005
1006 The number of tokens passed to the converter is inferred from the type hint by default,
1007 but can be explicitly controlled with :attr:`~.Parameter.n_tokens`. This is useful when
1008 the type signature doesn't match the desired CLI token consumption. When loading complex
1009 objects with multiple fields, it may also be useful to combine with :attr:`~.Parameter.accepts_keys`.
1010
1011 **Decorating Converters:** Converter functions can be decorated with :class:`.Parameter` to define
1012 reusable conversion behavior:
1013
1014 .. code-block:: python
1015
1016 @Parameter(n_tokens=1, accepts_keys=False)
1017 def load_from_id(type_, tokens):
1018 """Load object from database by ID."""
1019 return fetch_from_db(tokens[0].value)
1020
1021 @app.default
1022 def main(obj: Annotated[MyType, Parameter(converter=load_from_id)]):
1023 # Automatically inherits n_tokens=1 and accepts_keys=False
1024 pass
1025
1026 **Classmethod Support:** Converters can be classmethods. Use string references for class decoration
1027 or direct references in annotations. Classmethod signature should be ``(cls, tokens)`` instead of
1028 ``(type_, tokens)``:
1029
1030 .. code-block:: python
1031
1032 @Parameter(converter="from_env")
1033 class Config:
1034 @Parameter(n_tokens=1, accepts_keys=False)
1035 @classmethod
1036 def from_env(cls, tokens):
1037 env = tokens[0].value
1038 configs = {"dev": ("localhost", 8080), "prod": ("api.example.com", 443)}
1039 return cls(*configs[env])
1040
1041
1042 .. attribute:: validator
1043 :type: Union[None, Callable, str, Iterable[Union[Callable, str]]]
1044 :value: None
1045
1046 A function (or list of functions) that validates data returned by the :attr:`converter`.
1047
1048 .. code-block:: python
1049
1050 def validator(type_, value: Any) -> None:
1051 pass # Raise a TypeError, ValueError, or AssertionError here if data is invalid.
1052
1053 **Classmethod Support:** Validators can be classmethods. Use string references for class decoration
1054 or direct references in annotations.
1055
1056 .. code-block:: python
1057
1058 @Parameter(name="*", validator="validate")
1059 @dataclass
1060 class TextStyle:
1061 color: str
1062 bold: bool = False
1063 italic: bool = False
1064
1065 @classmethod
1066 def validate(cls, value):
1067 if value.bold and value.italic:
1068 raise ValueError("Cannot use both --bold and --italic together.")
1069
1070 .. attribute:: group
1071 :type: Union[None, str, Group, Iterable[Union[str, Group]]]
1072 :value: None
1073
1074 The group(s) that this parameter belongs to.
1075 This can be used to better organize the help-page, and/or to add additional conversion/validation logic (such as ensuring mutually-exclusive arguments).
1076
1077 If :obj:`None`, defaults to one of the following groups:
1078
1079 1. Parenting :attr:`.App.group_arguments` if the parameter is ``POSITIONAL_ONLY``.
1080 By default, this is ``Group("Arguments")``.
1081
1082 2. Parenting :attr:`.App.group_parameters` otherwise.
1083 By default, this is ``Group("Parameters")``.
1084
1085 See :ref:`Groups` for examples.
1086
1087 .. attribute:: negative
1088 :type: Union[None, str, Iterable[str]]
1089 :value: None
1090
1091 Name(s) for empty iterables or false boolean flags.
1092
1093 * For booleans, defaults to ``no-{name}`` (see :attr:`negative_bool`).
1094
1095 * For iterables, defaults to ``empty-{name}`` (see :attr:`negative_iterable`).
1096
1097 Set to an empty list or string to disable the creation of negative flags.
1098
1099 Example usage:
1100
1101 .. code-block:: python
1102
1103 from cyclopts import App, Parameter
1104 from typing import Annotated
1105
1106 app = App()
1107
1108 @app.default
1109 def main(*, verbose: Annotated[bool, Parameter(negative="--quiet")] = False):
1110 print(f"{verbose=}")
1111
1112 app()
1113
1114 .. code-block:: console
1115
1116 $ my-script --help
1117 Usage: main COMMAND [ARGS] [OPTIONS]
1118
1119 ╭─ Commands ─────────────────────────────────────────────────────╮
1120 │ --help -h Display this message and exit. │
1121 │ --version Display application version. │
1122 ╰────────────────────────────────────────────────────────────────╯
1123 ╭─ Parameters ───────────────────────────────────────────────────╮
1124 │ --verbose --quiet [default: False] │
1125 ╰────────────────────────────────────────────────────────────────╯
1126
1127 .. attribute:: negative_bool
1128 :type: Optional[str]
1129 :value: None
1130
1131 Prefix for negative boolean flags. Defaults to ``"no-"``.
1132
1133 .. attribute:: negative_iterable
1134 :type: Optional[str]
1135 :value: None
1136
1137 Prefix for empty iterables (like lists and sets) flags. Defaults to ``"empty-"``.
1138
1139 .. attribute:: negative_none
1140 :type: Optional[str]
1141 :value: None
1142
1143 Prefix for setting optional parameters to :obj:`None`.
1144 Not enabled by default (no prefixes set).
1145
1146 Example:
1147
1148 .. code-block:: python
1149
1150 from pathlib import Path
1151 from typing import Annotated
1152
1153 from cyclopts import App, Parameter
1154
1155 app = App(
1156 default_parameter=Parameter(negative_none="none-")
1157 )
1158
1159 @app.default
1160 def default(path: Path | None = Path("data.bin")):
1161 print(f"{path=}")
1162
1163 app()
1164
1165 .. code-block:: console
1166
1167 $ my-script
1168 path=PosixPath('data.bin')
1169
1170 $ my-script --path=cat.jpeg
1171 path=PosixPath('cat.jpeg')
1172
1173 $ my-script --none-path
1174 path=None
1175
1176 .. attribute:: allow_leading_hyphen
1177 :type: bool
1178 :value: False
1179
1180 Allow parsing non-numeric values that begin with a hyphen ``-``.
1181 This is disabled (:obj:`False`) by default, allowing for more helpful error messages for unknown CLI options.
1182
1183 .. attribute:: requires_equals
1184 :type: bool
1185 :value: False
1186
1187 Require long options to use ``=`` to separate the option name from its value (e.g., ``--option=value``).
1188 When enabled, the space-separated form ``--option value`` is rejected with a :class:`RequiresEqualsError`.
1189
1190 * Only applies to long-form options (those starting with ``--``).
1191 * Short options (e.g., ``-o value``) are **not** affected.
1192 * Boolean flags (e.g., ``--verbose``) work regardless of this setting.
1193 * Can be set app-wide via :attr:`.App.default_parameter`.
1194 * Cannot be combined with :attr:`consume_multiple` (raises :class:`ValueError`).
1195 To provide multiple values for a list parameter, repeat the option
1196 (e.g., ``--urls=a --urls=b``). To pass an empty iterable, use the
1197 negative flag (e.g., ``--empty-urls``).
1198
1199 .. code-block:: python
1200
1201 from cyclopts import App, Parameter
1202 from typing import Annotated
1203
1204 app = App()
1205
1206 @app.default
1207 def main(*, name: Annotated[str, Parameter(requires_equals=True)]):
1208 print(f"Hello {name}")
1209
1210 app()
1211
1212 .. code-block:: console
1213
1214 $ my-script --name=alice
1215 Hello alice
1216
1217 $ my-script --name alice
1218 ╭─ Error ───────────────────────────────────────────────────────╮
1219 │ Parameter --name requires a value assigned with `=`. Use │
1220 │ --name=VALUE. │
1221 ╰───────────────────────────────────────────────────────────────╯
1222
1223 .. attribute:: parse
1224 :type: Union[None, bool, str, re.Pattern]
1225 :value: None
1226
1227 Attempt to use this parameter while parsing.
1228 Annotated parameter **must** be keyword-only or have a default value.
1229 This is intended to be used with :ref:`meta apps <Meta App>` for injecting values.
1230
1231 * :obj:`True` - Parse this parameter from CLI tokens.
1232 * :obj:`False` - Do not parse; parameter will appear in the ``ignored`` dict from :meth:`.App.parse_args`.
1233 * :obj:`None` - Default behavior (parse).
1234 * :obj:`str` - A regex pattern; parse **if the pattern matches the parameter name**, otherwise skip. String patterns are automatically compiled to :class:`re.Pattern` for performance.
1235 * :class:`re.Pattern` - A pre-compiled regex pattern; same behavior as string patterns.
1236
1237 Regex patterns are primarily intended for use with :attr:`.App.default_parameter` to define app-wide skip patterns. For example, if we wanted to skip all fields that begin with an underscore ``_``:
1238
1239 .. code-block:: python
1240
1241 import re
1242 from cyclopts import App, Parameter
1243
1244 # Skip parsing underscore-prefixed KEYWORD_ONLY parameters (i.e. private parameters)
1245 # Both string and pre-compiled patterns are supported:
1246 app = App(default_parameter=Parameter(parse="^(?!_)"))
1247 # or: app = App(default_parameter=Parameter(parse=re.compile("^(?!_)")))
1248
1249 @app.default
1250 def main(visible: str, *, _injected: str = "default"):
1251 # _injected is NOT parsed from CLI; uses default value
1252 pass
1253
1254 .. attribute:: required
1255 :type: Optional[bool]
1256 :value: None
1257
1258 Indicates that the parameter must be supplied.
1259 Defaults to inferring from the function signature; i.e. :obj:`False` if the parameter has a default, :obj:`True` otherwise.
1260
1261 .. attribute:: show
1262 :type: Optional[bool]
1263 :value: None
1264
1265 Show this parameter on the help screen.
1266 Defaults to whether the parameter is :attr:`parsed <.Parameter.parse>` (usually :obj:`True`).
1267
1268 .. attribute:: show_default
1269 :type: Union[None, bool, str, Callable[[Any], Any]]
1270 :value: None
1271
1272 If a variable has a default, display the default on the help page.
1273 Defaults to :obj:`None`, similar to :obj:`True`, but will **not** display the default if it is :obj:`None`.
1274
1275 If set to a string, that string is displayed verbatim as the default value, regardless of the actual default.
1276 This is useful when the real default cannot be known at help-time (e.g. a value resolved at runtime):
1277
1278 .. code-block:: python
1279
1280 input_file: Annotated[Path | None, Parameter(show_default="automatic")] = None
1281
1282 Results in ``[default: automatic]`` on the help page.
1283
1284 If set to a function with signature:
1285
1286 .. code-block:: python
1287
1288 def formatter(value: Any) -> Any:
1289 ...
1290
1291 Then the function will be called with the default value, and the returned value will be used as the displayed default value.
1292
1293 Example formatting function:
1294
1295 .. code-block:: python
1296
1297 def hex_formatter(value: int) -> str
1298 """Will result in something like "[default: 0xFF]" instead of "[default: 255]"."""
1299 return f"0x{value:X}"
1300
1301 .. attribute:: show_choices
1302 :type: Optional[bool]
1303 :value: True
1304
1305 If a variable has a set of choices, display the choices on the help page.
1306
1307 .. attribute:: help
1308 :type: Optional[str]
1309 :value: None
1310
1311 Help string to be displayed on the help page.
1312 If not specified, defaults to the docstring.
1313
1314 .. attribute:: show_env_var
1315 :type: Optional[bool]
1316 :value: True
1317
1318 If a variable has :attr:`env_var` set, display the variable name on the help page.
1319
1320 .. attribute:: env_var
1321 :type: Union[None, str, Iterable[str]]
1322 :value: None
1323
1324 Fallback to environment variable(s) if CLI value not provided.
1325 If multiple environment variables are given, the left-most environment variable **with a set value** will be used.
1326 If no environment variable is set, Cyclopts will fallback to the function-signature default.
1327
1328 .. attribute:: env_var_split
1329 :type: Callable
1330 :value: cyclopts.env_var_split
1331
1332 Function that splits up the read-in :attr:`~cyclopts.Parameter.env_var` value.
1333 The function must have signature:
1334
1335 .. code-block:: python
1336
1337 def env_var_split(type_: type, val: str) -> list[str]:
1338 ...
1339
1340 where ``type_`` is the associated parameter type-hint, and ``val`` is the environment value.
1341
1342 .. attribute:: name_transform
1343 :type: Optional[Callable[[str], str]]
1344 :value: None
1345
1346 A function that converts python parameter names to their CLI command counterparts.
1347
1348 The function must have signature:
1349
1350 .. code-block:: python
1351
1352 def name_transform(s: str) -> str:
1353 ...
1354
1355 If :obj:`None` (default value), uses :func:`cyclopts.default_name_transform`.
1356
1357 .. attribute:: accepts_keys
1358 :type: Optional[bool]
1359 :value: None
1360
1361 If :obj:`False`, treat the user-defined class annotation similar to a tuple.
1362 Individual class sub-parameters will not be addressable by CLI keywords.
1363 The class will consume enough tokens to populate all required positional parameters.
1364
1365 Default behavior (``accepts_keys=True``):
1366
1367 .. code-block:: python
1368
1369 from cyclopts import App, Parameter
1370 from typing import Annotated
1371
1372 app = App()
1373
1374 class Image:
1375 def __init__(self, path, label):
1376 self.path = path
1377 self.label = label
1378
1379 def __repr__(self):
1380 return f"Image(path={self.path!r}, label={self.label!r})"
1381
1382 @app.default
1383 def main(image: Image):
1384 print(f"{image=}")
1385
1386 app()
1387
1388 .. code-block:: console
1389
1390 $ my-program --help
1391 Usage: main COMMAND [ARGS] [OPTIONS]
1392
1393 ╭─ Commands ──────────────────────────────────────────────────────────╮
1394 │ --help -h Display this message and exit. │
1395 │ --version Display application version. │
1396 ╰─────────────────────────────────────────────────────────────────────╯
1397 ╭─ Parameters ────────────────────────────────────────────────────────╮
1398 │ * IMAGE.PATH --image.path [required] │
1399 │ * IMAGE.LABEL --image.label [required] │
1400 ╰─────────────────────────────────────────────────────────────────────╯
1401
1402 $ my-program foo.jpg nature
1403 image=Image(path='foo.jpg', label='nature')
1404
1405 $ my-program --image.path foo.jpg --image.label nature
1406 image=Image(path='foo.jpg', label='nature')
1407
1408 Behavior when ``accepts_keys=False``:
1409
1410 .. code-block:: python
1411
1412 # Modify the default command function's signature.
1413 @app.default
1414 def main(image: Annotated[Image, Parameter(accepts_keys=False)]):
1415 print(f"{image=}")
1416
1417 .. code-block:: console
1418
1419 $ my-program --help
1420 Usage: main COMMAND [ARGS] [OPTIONS]
1421
1422 ╭─ Commands ──────────────────────────────────────────────────────────╮
1423 │ --help -h Display this message and exit. │
1424 │ --version Display application version. │
1425 ╰─────────────────────────────────────────────────────────────────────╯
1426 ╭─ Parameters ────────────────────────────────────────────────────────╮
1427 │ * IMAGE --image [required] │
1428 ╰─────────────────────────────────────────────────────────────────────╯
1429
1430 $ my-program foo.jpg nature
1431 image=Image(path='foo.jpg', label='nature')
1432
1433 $ my-program --image foo.jpg nature
1434 image=Image(path='foo.jpg', label='nature')
1435
1436 The ``accepts_keys=False`` option is commonly used with :attr:`~.Parameter.converter` and
1437 :attr:`~.Parameter.n_tokens`.
1438
1439 .. attribute:: consume_multiple
1440 :type: None | bool | int | Sequence[int]
1441 :value: None
1442
1443 Controls how many CLI tokens a list/iterable parameter consumes when specified **by keyword**.
1444 If the parameter is specified **positionally**, :attr:`.Parameter.consume_multiple` is ignored.
1445
1446 The following value types are supported:
1447
1448 * :obj:`False` (default) — only a single *element* worth of CLI tokens will be consumed per keyword occurrence.
1449 * :obj:`True` — all remaining CLI tokens will be consumed until the stream is exhausted or an option-like token is reached. Providing the keyword with no values creates an empty container.
1450 * :class:`int` — like :obj:`True`, but the integer specifies the **minimum** number of *elements* required. For example, ``consume_multiple=1`` requires at least one value (preventing empty lists), and ``consume_multiple=0`` is equivalent to :obj:`True`.
1451 * :class:`~collections.abc.Sequence`\[:class:`int`\] — a ``(min, max)`` pair (e.g. a tuple or list of two ints). All remaining CLI tokens are consumed greedily, and a :class:`ConsumeMultipleError` is raised if the number of elements is outside the ``(min, max)`` bounds.
1452
1453 **Example: consume_multiple=True**
1454
1455 .. code-block:: python
1456
1457 from cyclopts import App, Parameter
1458 from typing import Annotated
1459
1460 app = App()
1461
1462 @app.command
1463 def name_ext(
1464 name: str,
1465 ext: Annotated[list[str], Parameter(consume_multiple=True)],
1466 ):
1467 for extension in ext:
1468 print(f"{name}.{extension}")
1469
1470 app()
1471
1472 .. code-block:: console
1473
1474 $ my-program --name "my_file" --ext "txt" "pdf" # stream is exhausted
1475 my_file.txt
1476 my_file.pdf
1477
1478 $ my-program --ext "txt" "pdf" --name "my_file" # a keyword is reached
1479 my_file.txt
1480 my_file.pdf
1481
1482 When ``consume_multiple=True``, providing the keyword flag without any values will create an empty container, equivalent to using the :attr:`negative_iterable` prefix (e.g., ``--empty-ext``):
1483
1484 .. code-block:: console
1485
1486 $ my-program --name "my_file" --ext
1487 # No output - ext is an empty list []
1488
1489 $ my-program --name "my_file" --empty-ext
1490 # No output - ext is an empty list []
1491
1492 **Example: consume_multiple=1 (require at least one value)**
1493
1494 .. code-block:: python
1495
1496 from cyclopts import App, Parameter
1497 from typing import Annotated
1498
1499 app = App()
1500
1501 @app.default
1502 def main(
1503 urls: Annotated[list[str] | None, Parameter(consume_multiple=1)] = None,
1504 ):
1505 print(urls)
1506
1507 app()
1508
1509 .. code-block:: console
1510
1511 $ my-program --urls http://a.com http://b.com
1512 ['http://a.com', 'http://b.com']
1513
1514 $ my-program --urls
1515 ╭─ Error ────────────────────────────────────────────╮
1516 │ Parameter --urls requires an argument. │
1517 ╰────────────────────────────────────────────────────╯
1518
1519 **Example: consume_multiple=(1, 3) (min/max bounds)**
1520
1521 .. code-block:: python
1522
1523 from cyclopts import App, Parameter
1524 from typing import Annotated
1525
1526 app = App()
1527
1528 @app.default
1529 def main(
1530 files: Annotated[list[str], Parameter(consume_multiple=(1, 3))],
1531 ):
1532 print(f"Files: {files}")
1533
1534 app()
1535
1536 .. code-block:: console
1537
1538 $ my-program --files a.txt b.txt
1539 Files: ['a.txt', 'b.txt']
1540
1541 $ my-program --files a.txt b.txt c.txt d.txt
1542 ╭─ Error ─────────────────────────────────────────╮
1543 │ Parameter --files accepts at most 3 elements. │
1544 │ Got 4. │
1545 ╰─────────────────────────────────────────────────╯
1546
1547 In this example, ``--files`` raises a :class:`ConsumeMultipleError` if fewer than 1 or more than 3 values are provided.
1548
1549 **Example: consume_multiple=False (default)**
1550
1551 .. code-block:: python
1552
1553 from cyclopts import App
1554 from pathlib import Path
1555
1556 app = App()
1557
1558 @app.default
1559 def name_ext(name: str, ext: list[str]): # same as `ext: Annotated[list[str], Parameter(consume_multiple=False)]``
1560 for extension in ext:
1561 print(f"{name}.{extension}")
1562
1563 app()
1564
1565 .. code-block:: console
1566
1567 $ my-program --name "my_file" --ext "txt" "pdf"
1568 ╭─ Error ────────────────────────────────────────────╮
1569 │ Unused Tokens: ['pdf']. │
1570 ╰────────────────────────────────────────────────────╯
1571
1572 .. attribute:: json_dict
1573 :type: Optional[bool]
1574 :value: None
1575
1576 Allow for the parsing of json-dict-strings as data.
1577 If :obj:`None` (default behavior), acts like :obj:`True`, **unless** the annotated type is union'd with :obj:`str`.
1578 When :obj:`True`, data will be parsed as json if the following conditions are met:
1579
1580 1. The parameter is specified as a keyword option; e.g. ``--movie``.
1581
1582 2. The referenced parameter is dataclass-like.
1583
1584 3. The first character of the token is a ``{``.
1585
1586 .. attribute:: json_list
1587 :type: Optional[bool]
1588 :value: None
1589
1590 Allow for the parsing of json-list-strings as data.
1591 If :obj:`None` (default behavior), acts like :obj:`True`, **unless** the annotated type has each element type :obj:`str`.
1592 When :obj:`True`, data will be parsed as json if the following conditions are met:
1593
1594 1. The referenced parameter is iterable (not including :obj:`str`).
1595
1596 2. The first character of the token is a ``[``.
1597
1598 .. attribute:: count
1599 :type: bool
1600 :value: False
1601
1602 If :obj:`True`, count the number of times the flag appears instead of parsing a value.
1603 Each occurrence increments the count by 1 (e.g., ``-vvv`` results in ``3``).
1604
1605 Requirements and behavior:
1606
1607 * The parameter **must** have an :obj:`int` type hint (or ``Optional[int]``).
1608 * Short flags can be concatenated: ``-vvv`` is equivalent to ``-v -v -v``.
1609 * Long flags can be repeated: ``--verbose --verbose`` results in ``2``.
1610 * Negative flag variants (e.g., ``--no-verbose``) are **not** generated.
1611
1612 Common use case: verbosity levels.
1613
1614 .. code-block:: python
1615
1616 from cyclopts import App, Parameter
1617 from typing import Annotated
1618
1619 app = App()
1620
1621 @app.default
1622 def main(verbose: Annotated[int, Parameter(name="-v", count=True)] = 0):
1623 print(f"Verbosity level: {verbose}")
1624
1625 app()
1626
1627 .. code-block:: console
1628
1629 $ my-script -vvv
1630 Verbosity level: 3
1631
1632 See :ref:`Coercion Rules` for more details.
1633
1634 .. attribute:: allow_repeating
1635 :type: Optional[bool]
1636 :value: None
1637
1638 Controls whether a keyword option can be specified multiple times on the CLI (e.g., ``--foo a --foo b``).
1639
1640 * :obj:`None` (default): iterable types accumulate values, scalar types raise :exc:`RepeatArgumentError`.
1641 * :obj:`False`: always raise :exc:`RepeatArgumentError` on repeated options. Useful with :attr:`consume_multiple` to allow
1642 ``--foo a b c`` but disallow ``--foo a --foo b``.
1643 * :obj:`True`: always allow repeated options. Iterable types accumulate as usual. Scalar types
1644 use "last wins" semantics (the last value specified is used).
1645
1646 .. code-block:: python
1647
1648 from cyclopts import App, Parameter
1649 from typing import Annotated
1650
1651 app = App()
1652
1653 @app.default
1654 def main(
1655 values: Annotated[list[str], Parameter(consume_multiple=True, allow_repeating=False)],
1656 ):
1657 print(values)
1658
1659 app()
1660
1661 .. code-block:: console
1662
1663 $ my-script --values a b c
1664 ['a', 'b', 'c']
1665
1666 $ my-script --values a --values b
1667 ╭─ Error ──────────────────────────────────────────────────╮
1668 │ Parameter --values specified multiple times. │
1669 ╰─────────────────────────────────────────────────────────╯
1670
1671 .. attribute:: n_tokens
1672 :type: Optional[int]
1673 :value: None
1674
1675 Explicitly override the number of CLI tokens this parameter consumes.
1676
1677 By default, Cyclopts infers the token count from the parameter's type hint
1678 (e.g., :obj:`int` consumes 1 token, ``tuple[int, int]`` consumes 2, :obj:`list` consumes all remaining).
1679 This attribute allows you to override that inference, which is particularly useful when:
1680
1681 * Using custom converters that need a different token count than the type suggests.
1682 * Loading complex types from a single token (e.g., loading from a file path).
1683 * Implementing selection/lookup patterns where one token identifies an object.
1684
1685 Values:
1686
1687 * ``None`` (default): Infer token count from the type hint.
1688 * non-negative integer: Consume exactly that many tokens.
1689 * ``-1``: Consume all remaining tokens (similar to iterables).
1690
1691 For ``*args`` parameters, ``n_tokens`` specifies tokens **per element**.
1692 For example, ``n_tokens=2`` with 6 tokens creates 3 elements.
1693
1694 .. code-block:: python
1695
1696 from cyclopts import App, Parameter
1697 from typing import Annotated
1698
1699 class Config:
1700 def __init__(self, host: str, port: int):
1701 self.host = host
1702 self.port = port
1703
1704 def load_config(type_, tokens):
1705 # Load config from a file path (single token)
1706 filepath = tokens[0].value
1707 # ... load from file ...
1708 return Config("example.com", 8080)
1709
1710 app = App()
1711
1712 @app.default
1713 def main(
1714 config: Annotated[
1715 Config,
1716 Parameter(n_tokens=1, converter=load_config, accepts_keys=False)
1717 ]
1718 ):
1719 print(f"Connecting to {config.host}:{config.port}")
1720
1721 app()
1722
1723 .. code-block:: console
1724
1725 $ my-script --config prod.conf
1726 Connecting to example.com:8080
1727
1728 .. automethod:: combine
1729
1730 .. automethod:: default
1731
1732 .. autoclass:: cyclopts.Group
1733 :members: create_ordered
1734
1735 A group of parameters and/or commands in a CLI application.
1736
1737 .. attribute:: name
1738 :type: str
1739 :value: ""
1740
1741 Group name used for the help-page and for group-referenced-by-string.
1742 This is a title, so the first character should be capitalized.
1743 If a name is not specified, it will not be shown on the help-page.
1744
1745 .. attribute:: help
1746 :type: str
1747 :value: ""
1748
1749 Additional documentation shown on the help-page.
1750 This will be displayed inside the group's panel, above the parameters/commands.
1751
1752 .. attribute:: show
1753 :type: Optional[bool]
1754 :value: None
1755
1756 Show this group on the help-page.
1757 Defaults to :obj:`None`, which will only show the group if a ``name`` is provided.
1758
1759 .. attribute:: help_formatter
1760 :type: Union[None, Literal["default", "plain"], HelpFormatter]
1761 :value: None
1762
1763 Help formatter to use for rendering this group's help panel.
1764
1765 * If :obj:`None` (default), inherits from the :class:`.App`'s :attr:`~.App.help_formatter`.
1766
1767 * If ``"default"``, uses :class:`~cyclopts.help.DefaultFormatter`.
1768
1769 * If ``"plain"``, uses :class:`~cyclopts.help.PlainFormatter` for no-frills plain text output.
1770
1771 * If a callable (see :class:`~cyclopts.help.protocols.HelpFormatter` protocol), uses the provided formatter.
1772
1773 This allows per-group customization of help appearance:
1774
1775 .. code-block:: python
1776
1777 from cyclopts import App, Group, Parameter
1778 from cyclopts.help import DefaultFormatter, PanelSpec
1779 from typing import Annotated
1780
1781 app = App()
1782
1783 # Using string literal
1784 simple_group = Group(
1785 "Simple Options",
1786 help_formatter="plain"
1787 )
1788
1789 # Using custom formatter instance
1790 custom_group = Group(
1791 "Custom Options",
1792 help_formatter=DefaultFormatter(
1793 panel_spec=PanelSpec(border_style="red")
1794 )
1795 )
1796
1797 @app.default
1798 def main(
1799 opt1: Annotated[str, Parameter(group=simple_group)],
1800 opt2: Annotated[str, Parameter(group=custom_group)]
1801 ):
1802 pass
1803
1804 See :ref:`Help Customization` for detailed examples.
1805
1806 .. attribute:: sort_key
1807 :type: Any
1808 :value: None
1809
1810 Modifies group-panel display order on the help-page.
1811
1812 1. If :attr:`sort_key` is a generator, it will be consumed immediately with :func:`next` to get the actual value.
1813
1814 2. If :attr:`sort_key`, or any of it's contents, are ``Callable``, then invoke it ``sort_key(group)`` and apply the rules below.
1815
1816 3. The :class:`.App` default groups (:attr:`.App.group_command`, :attr:`.App.group_arguments`, :attr:`.App.group_parameters`) will be displayed first.
1817 If you want to further customize the ordering of these default groups, you can define custom values and they will be treated like any other group:
1818
1819 .. code-block:: python
1820
1821 from cyclopts import App, Group
1822
1823 app = App(
1824 group_parameters=Group("Parameters", sort_key=1),
1825 group_arguments=Group("Arguments", sort_key=2),
1826 group_commands=Group("Commands", sort_key=3),
1827 )
1828
1829
1830 @app.default
1831 def main(foo, /, bar):
1832 pass
1833
1834
1835 if __name__ == "__main__":
1836 app()
1837
1838 .. code-block:: console
1839
1840 $ python main.py --help
1841 Usage: main [ARGS] [OPTIONS]
1842
1843 ╭─ Parameters ──────────────────────────────────────────────────────────╮
1844 │ * BAR --bar [required] │
1845 ╰───────────────────────────────────────────────────────────────────────╯
1846 ╭─ Arguments ───────────────────────────────────────────────────────────╮
1847 │ * FOO [required] │
1848 ╰───────────────────────────────────────────────────────────────────────╯
1849 ╭─ Commands ────────────────────────────────────────────────────────────╮
1850 │ --help -h Display this message and exit. │
1851 │ --version Display application version. │
1852 ╰───────────────────────────────────────────────────────────────────────╯
1853
1854 4. For all groups with ``sort_key!=None``, sort them by ``(sort_key, group.name)``.
1855 That is, sort them by their ``sort_key``, and then break ties alphabetically.
1856 It is the user's responsibility that ``sort_key`` are comparable.
1857
1858 5. For all groups with ``sort_key==None`` (default value), sort them alphabetically after (4), :attr:`.App.group_commands`, :attr:`.App.group_arguments`, and :attr:`.App.group_parameters`.
1859
1860 Example usage:
1861
1862 .. code-block:: python
1863
1864 from cyclopts import App, Group
1865
1866 app = App()
1867
1868 @app.command(group=Group("4", sort_key=5))
1869 def cmd1():
1870 pass
1871
1872
1873 @app.command(group=Group("3", sort_key=lambda x: 10))
1874 def cmd2():
1875 pass
1876
1877
1878 @app.command(group=Group("2", sort_key=lambda x: None))
1879 def cmd3():
1880 pass
1881
1882
1883 @app.command(group=Group("1"))
1884 def cmd4():
1885 pass
1886
1887 app()
1888
1889 Resulting help-page:
1890
1891 .. code-block:: text
1892
1893 Usage: app COMMAND
1894
1895 ╭─ 4 ────────────────────────────────────────────────────────────────╮
1896 │ cmd1 │
1897 ╰────────────────────────────────────────────────────────────────────╯
1898 ╭─ 3 ────────────────────────────────────────────────────────────────╮
1899 │ cmd2 │
1900 ╰────────────────────────────────────────────────────────────────────╯
1901 ╭─ 1 ────────────────────────────────────────────────────────────────╮
1902 │ cmd4 │
1903 ╰────────────────────────────────────────────────────────────────────╯
1904 ╭─ 2 ────────────────────────────────────────────────────────────────╮
1905 │ cmd3 │
1906 ╰────────────────────────────────────────────────────────────────────╯
1907 ╭─ Commands ─────────────────────────────────────────────────────────╮
1908 │ --help,-h Display this message and exit. │
1909 │ --version Display application version. │
1910 ╰────────────────────────────────────────────────────────────────────╯
1911
1912 .. attribute:: default_parameter
1913 :type: Optional[Parameter]
1914 :value: None
1915
1916 Default :class:`.Parameter` in the parameter-resolution-stack that goes between :attr:`.App.default_parameter` and the function signature's :obj:`Annotated` :class:`.Parameter`.
1917 The provided :class:`.Parameter` is not allowed to have a :attr:`~.Parameter.group` value.
1918
1919 .. attribute:: validator
1920 :type: Optional[Callable]
1921 :value: None
1922
1923 A function (or list of functions) that validates an :class:`.ArgumentCollection`.
1924
1925 Example usage:
1926
1927 .. code-block:: python
1928
1929 def validator(argument_collection: ArgumentCollection):
1930 "Raise an exception if something is invalid."
1931
1932 The :class:`.ArgumentCollection` will contain all arguments that belong to that group.
1933 The validator(s) will **always be invoked**, regardless if any argument within the collection has token(s).
1934
1935 Validators are **not** invoked for command groups.
1936
1937 .. autoclass:: cyclopts.Token
1938
1939 .. attribute:: keyword
1940 :type: Optional[str]
1941 :value: None
1942
1943 **Unadulterated** user-supplied keyword like ``--foo`` or ``--foo.bar.baz``; ``None`` when token was pared positionally.
1944 Could also be something like ``tool.project.foo`` if from non-cli sources.
1945
1946 .. attribute:: value
1947 :type: str
1948 :value: ""
1949
1950 The parsed token value (unadulterated).
1951
1952 .. attribute:: source
1953 :type: str
1954 :value: ""
1955
1956 Where the token came from; used for error message purposes.
1957 Cyclopts uses the string ``cli`` for cli-parsed tokens.
1958
1959 .. attribute:: index
1960 :type: int
1961 :value: 0
1962
1963 The relative positional index in which the value was provided.
1964
1965 .. attribute:: keys
1966 :type: tuple[str, ...]
1967 :value: ()
1968
1969 The additional parsed **python** variable keys from :attr:`keyword`.
1970
1971 Only used for Arguments that take arbitrary keys.
1972
1973 .. attribute:: implicit_value
1974 :type: Any
1975 :value: cyclopts.UNSET
1976
1977 Final value that should be used instead of converting from :attr:`value`.
1978
1979 Commonly used for boolean flags.
1980
1981 Ignored if :obj:`~.UNSET`.
1982
1983 .. autoclass:: cyclopts.field_info.FieldInfo
1984
1985 .. autoclass:: cyclopts.Argument
1986 :members:
1987
1988 .. autoclass:: cyclopts.ArgumentCollection
1989 :members:
1990
1991 .. autoclass:: cyclopts.UNSET
1992
1993 .. autofunction:: cyclopts.default_name_transform
1994
1995 .. autofunction:: cyclopts.env_var_split
1996
1997 .. autofunction:: cyclopts.edit
1998
1999 .. autofunction:: cyclopts.run
2000
2001 .. autofunction:: cyclopts.resolve_returncode
2002
2003 .. autoclass:: cyclopts.CycloptsPanel
2004
2005 .. _API Validators:
2006
2007 ----------
2008 Validators
2009 ----------
2010 Cyclopts has several builtin validators for common CLI inputs.
2011
2012 .. autoclass:: cyclopts.validators.LimitedChoice
2013 :members:
2014
2015 .. autoclass:: cyclopts.validators.MutuallyExclusive
2016 :members:
2017
2018 .. autodata:: cyclopts.validators.mutually_exclusive
2019
2020 Instantiated version of :class:`~.validators.MutuallyExclusive`.
2021 Can be used directly in group validators:
2022
2023 .. code-block:: python
2024
2025 import cyclopts
2026 from cyclopts import Group
2027
2028 mutually_exclusive_group = Group(validator=cyclopts.validators.mutually_exclusive)
2029
2030 .. autodata:: cyclopts.validators.all_or_none
2031
2032 Group validator that enforces that either all parameters in the group must be supplied an argument, or none of them.
2033
2034 .. autoclass:: cyclopts.validators.Number
2035 :members:
2036
2037 .. autoclass:: cyclopts.validators.Path
2038 :members:
2039
2040
2041 .. _Annotated Types:
2042
2043 -----
2044 Types
2045 -----
2046 Cyclopts has builtin pre-defined annotated-types for common conversion and validation configurations.
2047 Most definitions in this section are simply predefined annotations for convenience:
2048
2049 .. code-block:: python
2050
2051 Annotated[..., Parameter(...)]
2052
2053 Custom classes that provide additional functionality beyond simple annotations will be noted.
2054
2055 Due to Cyclopts's advanced :class:`.Parameter` resolution engine, these annotations can themselves be annotated to further configure behavior. E.g:
2056
2057 .. code-block:: python
2058
2059 Annotated[PositiveInt, Parameter(...)]
2060
2061 .. _Annotated Path Types:
2062
2063 ^^^^
2064 Path
2065 ^^^^
2066 :class:`~pathlib.Path` annotated types for checking existence, type, and performing path-resolution.
2067 All of these types will also work on sequence of paths (e.g. ``tuple[Path, Path]`` or ``list[Path]``).
2068
2069 .. class:: cyclopts.types.StdioPath
2070
2071 .. note::
2072 This is a custom class, not a simple :obj:`~typing.Annotated` type alias.
2073
2074 Requires **Python 3.12+** due to :class:`~pathlib.Path` subclassing support.
2075
2076 A :class:`~pathlib.Path` subclass that treats ``-`` as stdin (for reading) or stdout (for writing).
2077 This follows `common Unix convention <https://clig.dev/#arguments-and-flags>`_.
2078
2079 :class:`StdioPath` is pre-configured with ``allow_leading_hyphen=True``, so ``-`` can be passed as an argument without being interpreted as an option.
2080
2081 .. attribute:: STDIO_STRING
2082 :type: str
2083 :value: "-"
2084
2085 Class attribute defining the string that triggers stdio behavior.
2086 Override in subclasses to use a different string.
2087
2088 .. attribute:: is_stdio
2089 :type: bool
2090
2091 Returns :obj:`True` if this path represents stdin/stdout (i.e., ``str(self) == STDIO_STRING``).
2092 Override this property in subclasses for custom matching logic (e.g., matching multiple strings).
2093
2094 Basic usage:
2095
2096 .. code-block:: python
2097
2098 from cyclopts import App
2099 from cyclopts.types import StdioPath
2100
2101 app = App()
2102
2103 @app.default
2104 def main(input_file: StdioPath):
2105 data = input_file.read_text()
2106 print(data.upper())
2107
2108 app()
2109
2110 .. code-block:: console
2111
2112 $ echo "hello" | python my_script.py -
2113 HELLO
2114
2115 $ python my_script.py data.txt
2116 <contents of data.txt uppercased>
2117
2118 To default to stdin/stdout when no argument is provided:
2119
2120 .. code-block:: python
2121
2122 @app.default
2123 def main(input_file: StdioPath = StdioPath("-")):
2124 data = input_file.read_text()
2125 print(data.upper())
2126
2127 See :ref:`Reading/Writing From File or Stdin/Stdout` for more examples.
2128
2129 **Subclassing**
2130
2131 To use a different trigger string or custom matching logic, subclass :class:`StdioPath`:
2132
2133 .. code-block:: python
2134
2135 from cyclopts.types import StdioPath
2136
2137 # Simple: different trigger string
2138 class StdinPath(StdioPath):
2139 STDIO_STRING = "STDIN"
2140
2141 class StdoutPath(StdioPath):
2142 STDIO_STRING = "STDOUT"
2143
2144 # Advanced: match multiple strings
2145 class MultiStdioPath(StdioPath):
2146 @property
2147 def is_stdio(self) -> bool:
2148 return str(self) in ("-", "STDIN", "STDOUT")
2149
2150 .. autodata:: cyclopts.types.ExistingPath
2151
2152 .. autodata:: cyclopts.types.NonExistentPath
2153
2154 .. autodata:: cyclopts.types.ResolvedPath
2155
2156 .. autodata:: cyclopts.types.ResolvedExistingPath
2157
2158 .. autodata:: cyclopts.types.Directory
2159
2160 .. autodata:: cyclopts.types.ExistingDirectory
2161
2162 .. autodata:: cyclopts.types.NonExistentDirectory
2163
2164 .. autodata:: cyclopts.types.ResolvedDirectory
2165
2166 .. autodata:: cyclopts.types.ResolvedExistingDirectory
2167
2168 .. autodata:: cyclopts.types.File
2169
2170 .. autodata:: cyclopts.types.ExistingFile
2171
2172 .. autodata:: cyclopts.types.NonExistentFile
2173
2174 .. autodata:: cyclopts.types.ResolvedFile
2175
2176 .. autodata:: cyclopts.types.ResolvedExistingFile
2177
2178 .. autodata:: cyclopts.types.BinPath
2179
2180 .. autodata:: cyclopts.types.ExistingBinPath
2181
2182 .. autodata:: cyclopts.types.NonExistentBinPath
2183
2184 .. autodata:: cyclopts.types.CsvPath
2185
2186 .. autodata:: cyclopts.types.ExistingCsvPath
2187
2188 .. autodata:: cyclopts.types.NonExistentCsvPath
2189
2190 .. autodata:: cyclopts.types.TxtPath
2191
2192 .. autodata:: cyclopts.types.ExistingTxtPath
2193
2194 .. autodata:: cyclopts.types.NonExistentTxtPath
2195
2196 .. autodata:: cyclopts.types.ImagePath
2197
2198 .. autodata:: cyclopts.types.ExistingImagePath
2199
2200 .. autodata:: cyclopts.types.NonExistentImagePath
2201
2202 .. autodata:: cyclopts.types.Mp4Path
2203
2204 .. autodata:: cyclopts.types.ExistingMp4Path
2205
2206 .. autodata:: cyclopts.types.NonExistentMp4Path
2207
2208 .. autodata:: cyclopts.types.JsonPath
2209
2210 .. autodata:: cyclopts.types.ExistingJsonPath
2211
2212 .. autodata:: cyclopts.types.NonExistentJsonPath
2213
2214 .. autodata:: cyclopts.types.TomlPath
2215
2216 .. autodata:: cyclopts.types.ExistingTomlPath
2217
2218 .. autodata:: cyclopts.types.NonExistentTomlPath
2219
2220 .. autodata:: cyclopts.types.YamlPath
2221
2222 .. autodata:: cyclopts.types.ExistingYamlPath
2223
2224 .. autodata:: cyclopts.types.NonExistentYamlPath
2225
2226 .. _Annotated Number Types:
2227
2228 ^^^^^^
2229 Number
2230 ^^^^^^
2231 Annotated types for checking common int/float value constraints.
2232 All of these types will also work on sequence of numbers (e.g. ``tuple[int, int]`` or ``list[float]``).
2233
2234 .. autodata:: cyclopts.types.PositiveFloat
2235
2236 .. autodata:: cyclopts.types.NonNegativeFloat
2237
2238 .. autodata:: cyclopts.types.NegativeFloat
2239
2240 .. autodata:: cyclopts.types.NonPositiveFloat
2241
2242 .. autodata:: cyclopts.types.NormFloat
2243
2244 .. autodata:: cyclopts.types.SignedNormFloat
2245
2246 .. autodata:: cyclopts.types.PositiveInt
2247
2248 .. autodata:: cyclopts.types.NonNegativeInt
2249
2250 .. autodata:: cyclopts.types.NegativeInt
2251
2252 .. autodata:: cyclopts.types.NonPositiveInt
2253
2254 .. autodata:: cyclopts.types.PercentInt
2255
2256 .. autodata:: cyclopts.types.UInt8
2257
2258 .. autodata:: cyclopts.types.HexUInt8
2259
2260 .. autodata:: cyclopts.types.Int8
2261
2262 .. autodata:: cyclopts.types.UInt16
2263
2264 .. autodata:: cyclopts.types.HexUInt16
2265
2266 .. autodata:: cyclopts.types.Int16
2267
2268 .. autodata:: cyclopts.types.UInt32
2269
2270 .. autodata:: cyclopts.types.HexUInt32
2271
2272 .. autodata:: cyclopts.types.Int32
2273
2274 .. autodata:: cyclopts.types.UInt64
2275
2276 .. autodata:: cyclopts.types.HexUInt64
2277
2278 .. autodata:: cyclopts.types.Int64
2279
2280 ^^^^
2281 Json
2282 ^^^^
2283 Annotated types for parsing a json-string from the CLI.
2284
2285 .. autodata:: cyclopts.types.Json
2286
2287 .. _API Config:
2288
2289
2290 ^^^
2291 Web
2292 ^^^
2293 Annotated types for common web-related values.
2294
2295 .. autodata:: cyclopts.types.Email
2296
2297 .. autodata:: cyclopts.types.Port
2298
2299 .. autodata:: cyclopts.types.URL
2300
2301 ---------------
2302 Help Formatting
2303 ---------------
2304 Cyclopts provides a flexible help formatting system for customizing the help-page's appearance.
2305
2306 .. autoclass:: cyclopts.help.protocols.HelpFormatter
2307 :members:
2308
2309
2310 .. autoclass:: cyclopts.help.DefaultFormatter
2311 :members:
2312
2313
2314 .. autoclass:: cyclopts.help.PlainFormatter
2315 :members:
2316
2317
2318 .. autoclass:: cyclopts.help.protocols.ColumnSpecBuilder
2319 :members:
2320
2321
2322 .. autoclass:: cyclopts.help.PanelSpec
2323 :members:
2324
2325
2326 .. autoclass:: cyclopts.help.TableSpec
2327 :members:
2328
2329
2330 .. autoclass:: cyclopts.help.ColumnSpec
2331 :members:
2332
2333
2334 .. autoclass:: cyclopts.help.NameRenderer
2335 :members:
2336
2337
2338 .. autoclass:: cyclopts.help.DescriptionRenderer
2339 :members:
2340
2341
2342 .. autoclass:: cyclopts.help.AsteriskRenderer
2343 :members:
2344
2345
2346 .. autoclass:: cyclopts.help.HelpPanel
2347 :members:
2348
2349
2350 .. autoclass:: cyclopts.help.HelpEntry
2351 :members:
2352
2353
2354 ------
2355 Config
2356 ------
2357 Cyclopts has builtin configuration classes to be used with :attr:`App.config <cyclopts.App.config>` for loading user-defined defaults in many common scenarios.
2358 All Cyclopts builtins index into the configuration file with the following rules:
2359
2360 1. Apply ``root_keys`` (if provided) to enter the project's configuration namespace.
2361
2362 2. Apply the command name(s) to enter the current command's configuration namespace.
2363
2364 3. Apply each key/value pair if CLI arguments have **not** been provided for that parameter.
2365
2366 .. autoclass:: cyclopts.config.Toml
2367
2368 Automatically read configuration from Toml file.
2369
2370 .. attribute:: path
2371 :type: str | pathlib.Path
2372
2373 Path to TOML configuration file.
2374
2375 .. attribute:: source
2376 :type: str | None
2377 :value: None
2378
2379 Identifier for the configuration source, used in error messages.
2380 If not provided, defaults to the absolute path of the configuration file.
2381
2382 .. attribute:: root_keys
2383 :type: Iterable[str]
2384 :value: None
2385
2386 The key or sequence of keys that lead to the root configuration structure for this app.
2387 For example, if referencing a ``pyproject.toml``, it is common to store all of your projects configuration under:
2388
2389 .. code-block:: toml
2390
2391 [tool.myproject]
2392
2393 So, your Cyclopts :class:`~cyclopts.App` should be configured as:
2394
2395 .. code-block:: python
2396
2397 app = cyclopts.App(config=cyclopts.config.Toml("pyproject.toml", root_keys=("tool", "myproject")))
2398
2399 .. attribute:: must_exist
2400 :type: bool
2401 :value: False
2402
2403 The configuration file MUST exist. Raises :class:`FileNotFoundError` if it does not exist.
2404
2405 .. attribute:: search_parents
2406 :type: bool
2407 :value: False
2408
2409 If ``path`` doesn't exist, iteratively search parenting directories for a same-named configuration file.
2410 Raises :class:`FileNotFoundError` if no configuration file is found.
2411
2412 .. attribute:: allow_unknown
2413 :type: bool
2414 :value: False
2415
2416 Allow for unknown keys. Otherwise, if an unknown key is provided, raises :class:`UnknownOptionError`.
2417 .. attribute:: use_commands_as_keys
2418 :type: bool
2419 :value: True
2420
2421 Use the sequence of commands as keys into the configuration.
2422
2423 For example, the following CLI invocation:
2424
2425 .. code-block:: console
2426
2427 $ python my-script.py my-command
2428
2429 Would search into ``["my-command"]`` for values.
2430
2431 .. autoclass:: cyclopts.config.Yaml
2432
2433 Automatically read configuration from YAML file.
2434
2435 .. attribute:: path
2436 :type: str | pathlib.Path
2437
2438 Path to YAML configuration file.
2439
2440 .. attribute:: source
2441 :type: str | None
2442 :value: None
2443
2444 Identifier for the configuration source, used in error messages.
2445 If not provided, defaults to the absolute path of the configuration file.
2446
2447 .. attribute:: root_keys
2448 :type: Iterable[str]
2449 :value: None
2450
2451 The key or sequence of keys that lead to the root configuration structure for this app.
2452 For example, if referencing a common ``config.yaml`` that is shared with other applications, it is common to store your projects configuration under a key like ``myproject:``.
2453
2454 Your Cyclopts :class:`~cyclopts.App` would be configured as:
2455
2456 .. code-block:: python
2457
2458 app = cyclopts.App(config=cyclopts.config.Yaml("config.yaml", root_keys="myproject"))
2459
2460 .. attribute:: must_exist
2461 :type: bool
2462 :value: False
2463
2464 The configuration file MUST exist. Raises :class:`FileNotFoundError` if it does not exist.
2465
2466 .. attribute:: search_parents
2467 :type: bool
2468 :value: False
2469
2470 If ``path`` doesn't exist, iteratively search parenting directories for a same-named configuration file.
2471 Raises :class:`FileNotFoundError` if no configuration file is found.
2472
2473 .. attribute:: allow_unknown
2474 :type: bool
2475 :value: False
2476
2477 Allow for unknown keys. Otherwise, if an unknown key is provided, raises :class:`UnknownOptionError`.
2478 .. attribute:: use_commands_as_keys
2479 :type: bool
2480 :value: True
2481
2482 Use the sequence of commands as keys into the configuration.
2483
2484 For example, the following CLI invocation:
2485
2486 .. code-block:: console
2487
2488 $ python my-script.py my-command
2489
2490 Would search into ``["my-command"]`` for values.
2491
2492
2493 .. autoclass:: cyclopts.config.Json
2494
2495 Automatically read configuration from Json file.
2496
2497 .. attribute:: path
2498 :type: str | pathlib.Path
2499
2500 Path to JSON configuration file.
2501
2502 .. attribute:: source
2503 :type: str | None
2504 :value: None
2505
2506 Identifier for the configuration source, used in error messages.
2507 If not provided, defaults to the absolute path of the configuration file.
2508 Can be customized to provide more descriptive error context.
2509
2510 Example:
2511
2512 .. code-block:: python
2513
2514 app = cyclopts.App(config=cyclopts.config.Json("config.json", source="production-config"))
2515
2516 .. attribute:: root_keys
2517 :type: Iterable[str]
2518 :value: None
2519
2520 The key or sequence of keys that lead to the root configuration structure for this app.
2521 For example, if referencing a common ``config.json`` that is shared with other applications, it is common to store your projects configuration under a key like ``"myproject":``.
2522
2523 Your Cyclopts :class:`~cyclopts.App` would be configured as:
2524
2525 .. code-block:: python
2526
2527 app = cyclopts.App(config=cyclopts.config.Json("config.json", root_keys="myproject"))
2528
2529 .. attribute:: must_exist
2530 :type: bool
2531 :value: False
2532
2533 The configuration file MUST exist. Raises :class:`FileNotFoundError` if it does not exist.
2534
2535 .. attribute:: search_parents
2536 :type: bool
2537 :value: False
2538
2539 If ``path`` doesn't exist, iteratively search parenting directories for a same-named configuration file.
2540 Raises :class:`FileNotFoundError` if no configuration file is found.
2541
2542 .. attribute:: allow_unknown
2543 :type: bool
2544 :value: False
2545
2546 Allow for unknown keys. Otherwise, if an unknown key is provided, raises :class:`UnknownOptionError`.
2547 .. attribute:: use_commands_as_keys
2548 :type: bool
2549 :value: True
2550
2551 Use the sequence of commands as keys into the configuration.
2552
2553 For example, the following CLI invocation:
2554
2555 .. code-block:: console
2556
2557 $ python my-script.py my-command
2558
2559 Would search into ``["my-command"]`` for values.
2560
2561
2562 .. autoclass:: cyclopts.config.Dict
2563
2564 Use an in-memory Python dictionary as configuration source.
2565
2566 .. attribute:: data
2567 :type: dict[str, Any]
2568
2569 The configuration dictionary.
2570
2571 .. attribute:: source
2572 :type: str
2573 :value: "dict"
2574
2575 Identifier for the configuration source, used in error messages.
2576
2577 .. attribute:: root_keys
2578 :type: Iterable[str]
2579 :value: ()
2580
2581 The key or sequence of keys that lead to the root configuration structure for this app.
2582
2583 .. attribute:: allow_unknown
2584 :type: bool
2585 :value: False
2586
2587 Allow for unknown keys. Otherwise, if an unknown key is provided, raises :class:`UnknownOptionError`.
2588
2589 .. attribute:: use_commands_as_keys
2590 :type: bool
2591 :value: True
2592
2593 Use the sequence of commands as keys into the configuration.
2594
2595
2596 .. autoclass:: cyclopts.config.Env
2597
2598 Automatically derive environment variable names to read configurations from.
2599
2600 For example, consider the following app:
2601
2602 .. code-block:: python
2603
2604 import cyclopts
2605
2606 app = cyclopts.App(config=cyclopts.config.Env("MY_SCRIPT_"))
2607
2608 @app.command
2609 def my_command(foo, bar):
2610 print(f"{foo=} {bar=}")
2611
2612 app()
2613
2614 If values for ``foo`` and ``bar`` are not supplied by the command line, the app will check
2615 the environment variables ``MY_SCRIPT_MY_COMMAND_FOO`` and ``MY_SCRIPT_MY_COMMAND_BAR``, respectively:
2616
2617 .. code-block:: console
2618
2619 $ python my_script.py my-command 1 2
2620 foo=1 bar=2
2621
2622 $ export MY_SCRIPT_MY_COMMAND_FOO=100
2623 $ python my_script.py my-command --bar=2
2624 foo=100 bar=2
2625 $ python my_script.py my-command 1 2
2626 foo=1 bar=2
2627
2628
2629 .. attribute:: prefix
2630 :type: str
2631 :value: ""
2632
2633 String to prepend to all autogenerated environment variable names.
2634 Typically ends in ``_``, and is something like ``MY_APP_``.
2635
2636 .. attribute:: source
2637 :type: str
2638 :value: "env"
2639
2640 Identifier for the configuration source, used in error messages and token tracking.
2641 Defaults to ``"env"``.
2642
2643 .. attribute:: command
2644 :type: bool
2645 :value: True
2646
2647 If :obj:`True`, add the command's name (uppercase) after :attr:`prefix`.
2648
2649 .. attribute:: show
2650 :type: bool
2651 :value: True
2652
2653 If :obj:`True`, then show the environment variables on the help-page.
2654
2655
2656 ----------
2657 Exceptions
2658 ----------
2659
2660 .. autoexception:: cyclopts.CycloptsError
2661 :show-inheritance:
2662 :members:
2663
2664 .. autoexception:: cyclopts.ValidationError
2665 :show-inheritance:
2666 :members:
2667
2668 .. autoexception:: cyclopts.UnknownOptionError
2669 :show-inheritance:
2670 :members:
2671
2672 .. autoexception:: cyclopts.CoercionError
2673 :show-inheritance:
2674 :members:
2675
2676 .. autoexception:: cyclopts.UnknownCommandError
2677 :show-inheritance:
2678 :members:
2679
2680 .. autoexception:: cyclopts.UnusedCliTokensError
2681 :show-inheritance:
2682 :members:
2683
2684 .. autoexception:: cyclopts.MissingArgumentError
2685 :show-inheritance:
2686 :members:
2687
2688 .. autoexception:: cyclopts.ConsumeMultipleError
2689 :show-inheritance:
2690 :members:
2691
2692 .. autoexception:: cyclopts.RequiresEqualsError
2693 :show-inheritance:
2694 :members:
2695
2696 .. autoexception:: cyclopts.RepeatArgumentError
2697 :show-inheritance:
2698 :members:
2699
2700 .. autoexception:: cyclopts.MixedArgumentError
2701 :show-inheritance:
2702 :members:
2703
2704 .. autoexception:: cyclopts.CommandCollisionError
2705 :show-inheritance:
2706 :members:
2707
2708 .. autoexception:: cyclopts.CombinedShortOptionError
2709 :show-inheritance:
2710 :members:
2711
2712 .. autoexception:: cyclopts.EditorError
2713 :show-inheritance:
2714 :members:
2715
2716 .. autoexception:: cyclopts.EditorNotFoundError
2717 :show-inheritance:
2718 :members:
2719
2720 .. autoexception:: cyclopts.EditorDidNotSaveError
2721 :show-inheritance:
2722 :members:
2723
2724 .. autoexception:: cyclopts.EditorDidNotChangeError
2725 :show-inheritance:
2726 :members:
2727
2728 ^^^^^^^^^^^^^^^
2729 Style Constants
2730 ^^^^^^^^^^^^^^^
2731
2732 Palette used by the built-in error messages. See
2733 :attr:`CycloptsError.msg <cyclopts.CycloptsError.msg>` for example usage.
2734
2735 .. autodata:: cyclopts.exceptions.STYLE_OFFENDING_VALUE
2736 .. autodata:: cyclopts.exceptions.STYLE_NAME
2737 .. autodata:: cyclopts.exceptions.STYLE_VALID_CHOICE
2738 .. autodata:: cyclopts.exceptions.STYLE_SUGGESTION
2739 .. autodata:: cyclopts.exceptions.STYLE_SOURCE