Debian Codegraph @

docs/source/parameters.rst

raw
1 ==========
2 Parameters
3 ==========
4
5 Typically, Cyclopts gets all the information it needs from object names, type hints, and the function docstring:
6
7 .. code-block:: python
8
9 from cyclopts import App
10
11 app = App(help="This is help for the root application.")
12
13 @app.command
14 def foo(value: int): # Cyclopts uses the ``value`` name and ``int`` type hint
15 """Cyclopts uses this short description for help.
16
17 Parameters
18 ----------
19 value: int
20 Cyclopts uses this description for ``value``'s help.
21 """
22
23 app()
24
25 Running the example:
26
27 .. code-block:: console
28
29 $ my-script --help
30 Usage: my-script COMMAND
31
32 This is help for the root application.
33
34 ╭─ Commands ──────────────────────────────────────────────────────────╮
35 │ foo Cyclopts uses this short description for help. │
36 │ --help,-h Display this message and exit. │
37 │ --version Display application version. │
38 ╰─────────────────────────────────────────────────────────────────────╯
39
40 $ my-script foo --help
41 Usage: my-script [ARGS] [OPTIONS]
42
43 Cyclopts uses this short description for help.
44
45 ╭─ Parameters ─────────────────────────────────────────────────────────────────────────╮
46 │ * VALUE --value Cyclopts uses this description for value's help. [required] │
47 ╰──────────────────────────────────────────────────────────────────────────────────────╯
48
49 This keeps the code as clean and terse as possible.
50 However, if more control is required, we can provide additional information by `annotating <https://docs.python.org/3/library/typing.html#typing.Annotated>`_ type hints with :class:`.Parameter`.
51
52 .. code-block:: python
53
54 from cyclopts import App, Parameter
55 from typing import Annotated
56
57 app = App()
58
59 @app.command
60 def foo(bar: Annotated[int, Parameter(...)]):
61 pass
62
63 app()
64
65 :class:`.Parameter` gives complete control on how Cyclopts processes the annotated parameter.
66 See the :ref:`API` page for all configurable options.
67 This page will investigate some of the more common use-cases.
68
69 .. note::
70 :class:`.Parameter` can also be used as a decorator.
71 This is :ref:`particularly useful for class definitions <Namespace Flattening>`.
72
73 ------
74 Naming
75 ------
76 Like :ref:`command names <Command Changing Name>`, CLI parameter names are derived from their python counterparts.
77 However, sometimes customization is needed.
78
79 .. _Parameters - Naming - Manual Naming:
80
81 ^^^^^^^^^^^^^
82 Manual Naming
83 ^^^^^^^^^^^^^
84 Parameter names (and their short forms) can be manually specified:
85
86 .. code-block:: python
87
88 from cyclopts import App, Parameter
89 from typing import Annotated
90
91 app = App()
92
93 @app.default
94 def main(
95 *,
96 foo: Annotated[str, Parameter(name=["--foo", "-f"])], # Adding a short-form
97 # Equivalently, you could have done Parameter(alias="-f")
98 bar: Annotated[str, Parameter(name="--something-else")],
99 ):
100 pass
101
102 app()
103
104 .. code-block:: console
105
106 $ my-script --help
107
108 Usage: main COMMAND [OPTIONS]
109 ╭─ Commands ──────────────────────────────────────────────╮
110 │ --help -h Display this message and exit. │
111 │ --version Display application version. │
112 ╰─────────────────────────────────────────────────────────╯
113 ╭─ Parameters ────────────────────────────────────────────╮
114 │ * --foo -f [required] │
115 │ * --something-else [required] │
116 ╰─────────────────────────────────────────────────────────╯
117
118 Manually set names via :attr:`Parameter.name <cyclopts.Parameter.name>` are not subject to :attr:`Parameter.name_transform <cyclopts.Parameter.name_transform>`.
119 Alternatively, additional names can be added to the Cyclopts-derived names (instead of completely overriding them) with :attr:`Parameter.alias <cyclopts.Parameter.alias>`.
120
121 .. note::
122 Docstrings should always use the **Python variable name** from the function signature.
123
124 .. code-block:: python
125
126 @app.default
127 def main(internal_name: Annotated[str, Parameter(name="external-name")]):
128 """Command description.
129
130 Parameters
131 ----------
132 internal_name: # Use the Python variable name
133 Help text here.
134 """
135
136 This follows standard Python documentation conventions; the parameter will still appear as ``--external-name`` on the CLI.
137
138 ^^^^^^^^^^^^^^
139 Name Transform
140 ^^^^^^^^^^^^^^
141 The name transform function that converts the python variable name to it's CLI counterpart can be configured by setting :attr:`Parameter.name_transform <cyclopts.Parameter.name_transform>` (defaults to :func:`.default_name_transform`).
142
143 .. code-block:: python
144
145 from cyclopts import App, Parameter
146 from typing import Annotated
147
148 app = App()
149
150 def name_transform(s: str) -> str:
151 return s.upper()
152
153 @app.default
154 def main(
155 *,
156 foo: Annotated[str, Parameter(name_transform=name_transform)],
157 bar: Annotated[str, Parameter(name_transform=name_transform)],
158 ):
159 pass
160
161 app()
162
163 .. code-block:: console
164
165 $ my-script --help
166 Usage: main COMMAND [OPTIONS]
167
168 ╭─ Commands ──────────────────────────────────────────────╮
169 │ --help -h Display this message and exit. │
170 │ --version Display application version. │
171 ╰─────────────────────────────────────────────────────────╯
172 ╭─ Parameters ────────────────────────────────────────────╮
173 │ * --FOO [required] │
174 │ * --BAR [required] │
175 ╰─────────────────────────────────────────────────────────╯
176
177 Notice how the parameter is now ``--FOO`` instead of the standard ``--foo``.
178
179 .. note::
180 The returned string is **before** the standard ``--`` is prepended.
181
182 Generally, it is not very useful to set the name transform on **individual** parameters; it would be easier/clearer :ref:`to manually specify the name <Parameters - Naming - Manual Naming>`.
183 However, we can change the default name transform for the **entire app** by configuring the app's :ref:`default_parameter <Default Parameter>`.
184
185 To change the :attr:`~cyclopts.Parameter.name_transform` across your entire app, add the following to your :class:`~cyclopts.App` configuration:
186
187 .. code-block:: python
188
189 app = App(
190 default_parameter=Parameter(name_transform=my_custom_name_transform),
191 )
192
193 ----
194 Help
195 ----
196 It is recommended to use docstrings for your parameter help, but if necessary, you can explicitly set a help string:
197
198 .. code-block:: python
199
200 @app.command
201 def foo(value: Annotated[int, Parameter(help="THIS IS USED.")]):
202 """
203 Parameters
204 ----------
205 value: int
206 This description is not used; got overridden.
207 """
208
209 .. code-block:: console
210
211 $ my-script foo --help
212 ╭─ Parameters ──────────────────────────────────────────────────╮
213 │ * VALUE,--value THIS IS USED. [required] │
214 ╰───────────────────────────────────────────────────────────────╯
215
216 .. _Converters:
217
218 ----------
219 Converters
220 ----------
221
222 Cyclopts has a powerful coercion engine that automatically converts CLI string tokens to the types hinted in a function signature.
223 However, sometimes a custom :attr:`~.Parameter.converter` is required to transform the input string tokens into the desired type.
224
225 Lets consider a case where we want the user to specify a file size, and we want to allows suffixes like `"MB"`.
226
227 .. code-block:: python
228
229 from cyclopts import App, Parameter, Token
230 from typing import Annotated, Sequence
231 from pathlib import Path
232
233 app = App()
234
235 mapping = {
236 "kb": 1024,
237 "mb": 1024 * 1024,
238 "gb": 1024 * 1024 * 1024,
239 }
240
241 def byte_units(type_, tokens: Sequence[Token]) -> int:
242 # type_ is ``int``,
243 value = tokens[0].value.lower()
244 try:
245 return type_(value) # If this works, it didn't have a suffix.
246 except ValueError:
247 pass
248 number, suffix = value[:-2], value[-2:]
249 return int(number) * mapping[suffix]
250
251 @app.command
252 def zero(file: Path, size: Annotated[int, Parameter(converter=byte_units)]):
253 """Creates a file of all-zeros."""
254 print(f"Writing {size} zeros to {file}.")
255 file.write_bytes(bytes(size))
256
257 app()
258
259 .. code-block:: console
260
261 $ my-script zero out.bin 100
262 Writing 100 zeros to out.bin.
263
264 $ my-script zero out.bin 1kb
265 Writing 1024 zeros to out.bin.
266
267 $ my-script zero out.bin 3mb
268 Writing 3145728 zeros to out.bin.
269
270 The converter function gets the annotated type, and the :class:`.Token` s parsed for this argument.
271 Tokens are Cyclopt's way of bookkeeping user inputs; in the last command the ``tokens`` object would look like:
272
273 .. code-block:: python
274
275 # tokens is a length-1 tuple. The variable "size" only takes in 1 token:
276 tuple(
277 Token(
278 keyword=None, # "3mb" was provided positionally, not by keyword
279 value='3mb', # The string from the command line
280 source='cli', # The value came from the command line, as opposed to other Cyclopts mechanisms.
281 index=0, # For the variable "size", this is the first (0th) token.
282 ),
283 )
284
285 ^^^^^^^^^^^^^^^^^^^^^^^^
286 Controlling Token Count
287 ^^^^^^^^^^^^^^^^^^^^^^^^
288
289 By default, Cyclopts infers how many tokens a parameter should consume from its type hint.
290 For example, :obj:`int` consumes 1 token, ``tuple[int, int]`` consumes 2, and ``list[int]`` consumes all remaining tokens.
291 When using custom converters, you may need to override this inference with :attr:`.Parameter.n_tokens`:
292
293 .. code-block:: python
294
295 from cyclopts import App, Parameter
296 from typing import Annotated
297
298 class Point:
299 def __init__(self, x: int, y: int):
300 self.x = x
301 self.y = y
302
303 def parse_point(type_, tokens):
304 """Parse a coordinate string like '10,20' into a Point."""
305 x, y = tokens[0].value.split(",")
306 return Point(int(x), int(y))
307
308 app = App()
309
310 @app.default
311 def main(pos: Annotated[Point, Parameter(n_tokens=1, converter=parse_point, accepts_keys=False)]):
312 """Without n_tokens=1, Cyclopts would expect 2 tokens based on Point's __init__ signature."""
313 print(f"Position: ({pos.x}, {pos.y})")
314
315 app()
316
317 .. code-block:: console
318
319 $ my-script --pos 10,20
320 Position: (10, 20)
321
322 The :attr:`.Parameter.accepts_keys` parameter prevents Cyclopts from generating nested options like
323 ``--pos.x`` and ``--pos.y``.
324
325 Alternative to the above syntax, you can directly **decorate the converter function** itself with :class:`.Parameter` to define
326 its behavior. This keeps all the information organized in a single location.
327
328 .. code-block:: python
329
330 from cyclopts import App, Parameter
331 from typing import Annotated
332
333 class Point:
334 def __init__(self, x: int, y: int):
335 self.x = x
336 self.y = y
337
338 @Parameter(n_tokens=1, accepts_keys=False)
339 def parse_point(type_, tokens):
340 """Parse a coordinate string like '10,20' into a Point."""
341 x, y = tokens[0].value.split(",")
342 return Point(int(x), int(y))
343
344 app = App()
345
346 @app.default
347 def main(pos: Annotated[Point, Parameter(converter=parse_point)]):
348 """The converter's n_tokens and accepts_keys are automatically inherited."""
349 print(f"Position: ({pos.x}, {pos.y})")
350
351 app()
352
353 .. code-block:: console
354
355 $ my-script --pos 10,20
356 Position: (10, 20)
357
358 You can also decorate classes directly with the converter:
359
360 .. code-block:: python
361
362 @Parameter(converter=parse_point)
363 class Point:
364 def __init__(self, x: int, y: int):
365 self.x = x
366 self.y = y
367
368 @app.default
369 def main(pos: Point):
370 """No Annotated wrapper needed - converter is part of the class definition."""
371 print(f"Position: ({pos.x}, {pos.y})")
372
373 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
374 Using Classmethods as Converters
375 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
376
377 Converter functions are often closely associated with the class they create, making classmethods a natural choice. Cyclopts supports using classmethods as converters through forward string references (for class decoration) or direct references (for function annotations):
378
379 .. code-block:: python
380
381 from cyclopts import App, Parameter
382 from typing import Annotated
383
384 # Decorate the classmethod to configure n_tokens and accepts_keys
385 # (decorator must go above @classmethod)
386 @Parameter(converter="parse")
387 class Point:
388 def __init__(self, x: int, y: int):
389 self.x = x
390 self.y = y
391
392 @Parameter(n_tokens=1, accepts_keys=False)
393 @classmethod
394 def parse(cls, tokens):
395 """Parse a coordinate string like '10,20' into a Point.
396
397 Note: classmethod signature is (cls, tokens), not (type_, tokens)
398 """
399 x, y = tokens[0].value.split(",")
400 return cls(int(x), int(y))
401
402 app = App()
403
404 @app.default
405 def main(pos: Point):
406 """The classmethod's n_tokens and accepts_keys are automatically inherited."""
407 print(f"Position: ({pos.x}, {pos.y})")
408
409 app()
410
411 .. code-block:: console
412
413 $ my-script --pos 10,20
414 Position: (10, 20)
415
416 Alternatively, you can reference the classmethod directly in function annotations:
417
418 .. code-block:: python
419
420 class Point:
421 def __init__(self, x: int, y: int):
422 self.x = x
423 self.y = y
424
425 @classmethod
426 def parse(cls, tokens):
427 x, y = tokens[0].value.split(",")
428 return cls(int(x), int(y))
429
430 @app.default
431 def main(pos: Annotated[Point, Parameter(converter=Point.parse, n_tokens=1, accepts_keys=False)]):
432 print(f"Position: ({pos.x}, {pos.y})")
433
434 **Note on classmethod signatures**: Classmethods used as converters should have the signature ``(cls, tokens)`` rather than ``(type_, tokens)``. Cyclopts automatically detects bound methods and calls them with just the ``tokens`` parameter, since ``cls`` is already bound.
435
436 ----------------
437 Validating Input
438 ----------------
439 Just because data is of the correct type, doesn't mean it's valid.
440 If we had a program that accepts integer user age as an input, ``-1`` is an integer, but not a valid age.
441
442 .. code-block:: python
443
444 from cyclopts import App, Parameter
445 from typing import Annotated
446
447 app = App()
448
449 def validate_age(type_, value):
450 if value < 0:
451 raise ValueError("Negative ages not allowed.")
452 if value > 150:
453 raise ValueError("You are too old to be using this application.")
454
455 @app.default
456 def allowed_to_buy_alcohol(age: Annotated[int, Parameter(validator=validate_age)]):
457 print("Under 21: prohibited." if age < 21 else "Good to go!")
458
459 app()
460
461 .. code-block:: console
462
463 $ my-script 30
464 Good to go!
465
466 $ my-script 10
467 Under 21: prohibited.
468
469 $ my-script -1
470 ╭─ Error ──────────────────────────────────────────────────────────────────────╮
471 │ Invalid value "-1" for "AGE". Negative ages not allowed. │
472 ╰──────────────────────────────────────────────────────────────────────────────╯
473
474 $ my-script 200
475 ╭─ Error ──────────────────────────────────────────────────────────────────────╮
476 │ Invalid value "200" for "AGE". You are too old to be using this application. │
477 ╰──────────────────────────────────────────────────────────────────────────────╯
478
479 Certain builtin error types (:exc:`ValueError`, :exc:`TypeError`, :exc:`AssertionError`) will be re-interpreted by Cyclopts and formatted into a prettier message for the application user.
480
481 Cyclopts has some :ref:`builtin validators <Parameter Validators>` for common situations
482 We can create a similar app as above:
483
484 .. code-block:: python
485
486 from cyclopts import App, Parameter, validators
487 from typing import Annotated
488
489 app = App()
490
491 @app.default
492 def allowed_to_buy_alcohol(age: Annotated[int, Parameter(validator=validators.Number(gte=0, lte=150))]):
493 # gte - greater than or equal to
494 # lte - less than or equal to
495 print("Under 21: prohibited." if age < 21 else "Good to go!")
496
497 app()
498
499 Taking this one step further, Cyclopts has some :ref:`builtin convenience types <Annotated Types>`. If we didn't care about the upper age bound, we could simplify the application to:
500
501 .. code-block:: python
502
503 from cyclopts import App
504 from cyclopts.types import NonNegativeInt
505
506 app = App()
507
508 @app.default
509 def allowed_to_buy_alcohol(age: NonNegativeInt):
510 print("Under 21: prohibited." if age < 21 else "Good to go!")
511
512 app()
513
514 --------------------
515 Parameter Resolution
516 --------------------
517 Cyclopts can combine multiple :class:`.Parameter` annotations together.
518 Say you want to define a new :obj:`int` type that uses the :ref:`byte-centric converter from above<Converters>`.
519
520 We can define the type:
521
522 .. code-block:: python
523
524 ByteSize = Annotated[int, Parameter(converter=byte_units)]
525
526 We can then either directly annotate a function parameter with this:
527
528 .. code-block:: python
529
530 @app.command
531 def zero(size: ByteSize):
532 pass
533
534 or even stack annotations to add additional features, like a validator:
535
536 .. code-block:: python
537
538 def must_be_multiple_of_4096(type_, value):
539 assert value % 4096 == 0, "Size must be a multiple of 4096"
540
541
542 @app.command
543 def zero(size: Annotated[ByteSize, Parameter(validator=must_be_multiple_of_4096)]):
544 pass
545
546 Python automatically flattens out annotations, so this is interpreted as:
547
548 .. code-block:: python
549
550 Annotated[ByteSize, Parameter(converter=byte_units), Parameter(validator=must_be_multiple_of_4096)]
551
552 Cyclopts will search **right-to-left** for **set** parameter attributes until one is found. I.e. right-most parameter attributes have the highest priority.
553
554 .. code-block:: console
555
556 $ my-script 1234
557 ╭─ Error ──────────────────────────────────────────────────────────────────────╮
558 │ Invalid value "1234" for "SIZE". Size must be a multiple of 4096 │
559 ╰──────────────────────────────────────────────────────────────────────────────╯
560
561 See :ref:`Parameter Resolution Order<Parameter Resolution Order>` for more details.