Debian Codegraph @

docs/source/groups.rst

raw
1 .. _Groups:
2
3 ======
4 Groups
5 ======
6 Groups offer a way of organizing parameters and commands on the help-page; for example:
7
8 .. code-block:: console
9
10 Usage: my-script.py create [OPTIONS]
11
12 ╭─ Vehicle (choose one) ───────────────────────────────────────────────────────╮
13 │ --car [default: False] │
14 │ --truck [default: False] │
15 ╰──────────────────────────────────────────────────────────────────────────────╯
16 ╭─ Engine ─────────────────────────────────────────────────────────────────────╮
17 │ --hp [default: 200] │
18 │ --cylinders [default: 6] │
19 ╰──────────────────────────────────────────────────────────────────────────────╯
20 ╭─ Wheels ─────────────────────────────────────────────────────────────────────╮
21 │ --wheel-diameter [default: 18] │
22 │ --rims,--no-rims [default: False] │
23 ╰──────────────────────────────────────────────────────────────────────────────╯
24
25 They also provide an additional abstraction layer that :ref:`validators <API Validators>` can operate on.
26
27 Groups can be created in two ways:
28
29 1. Explicitly creating a :class:`.Group` object.
30
31 2. Implicitly with a **string**.
32 This will implicitly create a group, ``Group(my_str_group_name)``, if it doesn't exist.
33 If there exists a :class:`.Group` object with the same name within the command/parameter context, it will join that group.
34
35 .. warning::
36 While convenient and terse, mistyping a group name will unintentionally create a new group!
37
38 Every command and parameter belongs to at least one group.
39
40 Group(s) can be provided to the ``group`` keyword argument of :meth:`app.command <cyclopts.App.command>` and :class:`.Parameter`.
41 Like :class:`.Parameter`, the :class:`.Group` class itself only marks objects with metadata; the group does **not** contain direct references to it's members.
42 This means that groups can be reused across commands.
43
44 --------------
45 Command Groups
46 --------------
47 An example of using groups to organize commands:
48
49 .. code-block:: python
50
51 from cyclopts import App
52
53 app = App()
54
55 # Change the group of "--help" and "--version" to the implicitly created "Admin" group.
56 app["--help"].group = "Admin"
57 app["--version"].group = "Admin"
58
59 @app.command(group="Admin")
60 def info():
61 """Print debugging system information."""
62 print("Displaying system info.")
63
64 @app.command
65 def download(path, url):
66 """Download a file."""
67 print(f"Downloading {url} to {path}.")
68
69 @app.command
70 def upload(path, url):
71 """Upload a file."""
72 print(f"Downloading {url} to {path}.")
73
74 app()
75
76 .. code-block:: console
77
78 $ python my-script.py --help
79 Usage: my-script.py COMMAND
80
81 ╭─ Admin ──────────────────────────────────────────────────────────────────────╮
82 │ info Print debugging system information. │
83 │ --help,-h Display this message and exit. │
84 │ --version Display application version. │
85 ╰──────────────────────────────────────────────────────────────────────────────╯
86 ╭─ Commands ───────────────────────────────────────────────────────────────────╮
87 │ download Download a file. │
88 │ upload Upload a file. │
89 ╰──────────────────────────────────────────────────────────────────────────────╯
90
91 The default group is defined by the registering app's :attr:`.App.group_commands`, which defaults to a group named ``"Commands"``.
92
93 .. _Parameter Groups:
94
95 ----------------
96 Parameter Groups
97 ----------------
98 Like commands above, parameter groups allow us to organize parameters on the help page.
99 They also allow us to add additional inter-parameter validators (e.g. mutually-exclusive parameters).
100 An example of using groups with parameters:
101
102 .. code-block:: python
103
104 from cyclopts import App, Group, Parameter, validators
105 from typing import Annotated
106
107 app = App()
108
109 vehicle_type_group = Group(
110 "Vehicle (choose one)",
111 default_parameter=Parameter(negative=""), # Disable "--no-" flags
112 validator=validators.MutuallyExclusive(), # Only one option is allowed to be selected.
113 )
114
115 @app.command
116 def create(
117 *, # force all subsequent variables to be keyword-only
118 # Using an explicitly created group object.
119 car: Annotated[bool, Parameter(group=vehicle_type_group)] = False,
120 truck: Annotated[bool, Parameter(group=vehicle_type_group)] = False,
121 # Implicitly creating an "Engine" group.
122 hp: Annotated[float, Parameter(group="Engine")] = 200,
123 cylinders: Annotated[int, Parameter(group="Engine")] = 6,
124 # You can explicitly create groups in-line.
125 wheel_diameter: Annotated[float, Parameter(group=Group("Wheels"))] = 18,
126 # Groups within the function signature can always be referenced with a string.
127 rims: Annotated[bool, Parameter(group="Wheels")] = False,
128 ):
129 pass
130
131 app()
132
133 .. code-block:: console
134
135 $ python my-script.py create --help
136 Usage: my-script.py create [OPTIONS]
137
138 ╭─ Engine ──────────────────────────────────────────────────────╮
139 │ --hp [default: 200] │
140 │ --cylinders [default: 6] │
141 ╰───────────────────────────────────────────────────────────────╯
142 ╭─ Vehicle (choose one) ────────────────────────────────────────╮
143 │ --car [default: False] │
144 │ --truck [default: False] │
145 ╰───────────────────────────────────────────────────────────────╯
146 ╭─ Wheels ──────────────────────────────────────────────────────╮
147 │ --wheel-diameter [default: 18] │
148 │ --rims --no-rims [default: False] │
149 ╰───────────────────────────────────────────────────────────────╯
150
151 $ python my-script.py create --car --truck
152 ╭─ Error ───────────────────────────────────────────────────────╮
153 │ Invalid values for group "Vehicle (choose one)". Mutually │
154 │ exclusive arguments: {--car, --truck} │
155 ╰───────────────────────────────────────────────────────────────╯
156
157 In this example, we use the :class:`~.validators.MutuallyExclusive` validator to make it so the user can only specify ``--car`` or ``--truck``.
158
159 The default groups are defined by the registering app:
160
161 * :attr:`.App.group_arguments` for positional-only arguments, which defaults to a group named ``"Arguments"``.
162
163 * :attr:`.App.group_parameters` for all other parameters, which defaults to a group named ``"Parameters"``.
164
165 ----------
166 Validators
167 ----------
168 Group validators offer a way of jointly validating group parameter members of CLI-provided values.
169 Groups with an empty name, or with ``show=False``, are a way of using group validators without impacting the help-page.
170
171 .. code-block:: python
172
173 from cyclopts import App, Group, Parameter, validators
174 from typing import Annotated
175
176 app = App()
177
178 mutually_exclusive = Group(
179 # This Group has no name, so it won't impact the help page.
180 validator=validators.MutuallyExclusive(),
181 # show_default=False - Showing "[default: False]" isn't too meaningful for mutually-exclusive options.
182 # negative="" - Don't create a "--no-" flag
183 default_parameter=Parameter(show_default=False, negative=""),
184 )
185
186 @app.command
187 def foo(
188 car: Annotated[bool, Parameter(group=(app.group_parameters, mutually_exclusive))] = False,
189 truck: Annotated[bool, Parameter(group=(app.group_parameters, mutually_exclusive))] = False,
190 ):
191 print(f"{car=} {truck=}")
192
193 app()
194
195 .. code-block:: console
196
197 $ python demo.py foo --help
198 Usage: demo.py foo [ARGS] [OPTIONS]
199
200 ╭─ Parameters ──────────────────────────────────────────────────────╮
201 │ CAR,--car │
202 │ TRUCK,--truck │
203 ╰───────────────────────────────────────────────────────────────────╯
204
205 $ python demo.py foo --car
206 car=True truck=False
207
208 $ python demo.py foo --truck
209 car=False truck=True
210
211 $ python demo.py foo --car --truck
212 ╭─ Error ───────────────────────────────────────────────────────────╮
213 │ Mutually exclusive arguments: {--car, --truck} │
214 ╰───────────────────────────────────────────────────────────────────╯
215
216 See :attr:`.Group.validator` for details.
217
218 Cyclopts has some :ref:`builtin group-validators for common use-cases.<Group Validators>`
219
220 ---------
221 Help Page
222 ---------
223 Groups form titled panels on the help-page.
224
225 Groups with an empty name, or with :attr:`show=False <.Group.show>`, are **not** shown on the help-page.
226 This is useful for applying additional grouping logic (such as applying a :class:`.LimitedChoice` validator) without impacting the help-page.
227
228 By default, the ordering of panels is **alphabetical**.
229 However, the sorting can be manipulated by :attr:`.Group.sort_key`. See it's documentation for usage.
230
231 The :meth:`.Group.create_ordered` convenience classmethod creates a :class:`.Group` with a :attr:`~.Group.sort_key` value drawn drawn from a global monotonically increasing counter.
232 This means that the order in the help-page will match the order that the groups were instantiated.
233
234 .. code-block:: python
235
236 from cyclopts import App, Group
237
238 app = App()
239
240 plants = Group.create_ordered("Plants")
241 animals = Group.create_ordered("Animals")
242 fungi = Group.create_ordered("Fungi")
243
244 @app.command(group=animals)
245 def zebra():
246 pass
247
248 @app.command(group=plants)
249 def daisy():
250 pass
251
252 @app.command(group=fungi)
253 def portobello():
254 pass
255
256 app()
257
258 .. code-block:: console
259
260 $ my-script --help
261
262 Usage: scratch.py COMMAND
263
264 ╭─ Plants ───────────────────────────────────────────────────────────╮
265 │ daisy │
266 ╰────────────────────────────────────────────────────────────────────╯
267 ╭─ Animals ──────────────────────────────────────────────────────────╮
268 │ zebra │
269 ╰────────────────────────────────────────────────────────────────────╯
270 ╭─ Fungi ────────────────────────────────────────────────────────────╮
271 │ portobello │
272 ╰────────────────────────────────────────────────────────────────────╯
273 ╭─ Commands ─────────────────────────────────────────────────────────╮
274 │ --help -h Display this message and exit. │
275 │ --version Display application version. │
276 ╰────────────────────────────────────────────────────────────────────╯
277
278 Even when using :meth:`.Group.create_ordered`, a :attr:`~.Group.sort_key` can still be supplied; the global counter will only be used to break sorting ties.