Debian Codegraph @

docs/source/parameter_validators.rst

raw
1 .. _Parameter Validators:
2
3 ====================
4 Parameter Validators
5 ====================
6 In CLI applications, users have the freedom to input a wide range of data.
7 This flexibility can lead to inputs the application does not expect.
8 By coercing the input into a data type (like an :obj:`int`), we are already limiting the input to a certain degree (e.g. "foo" cannot be coerced into an integer).
9 To further restrict the user input, you can populate the :attr:`~.Parameter.validator` field of :class:`.Parameter`.
10
11 A validator is any callable object (such as a function) that has the signature:
12
13 .. code-block:: python
14
15 def validator(type_, value: Any) -> None:
16 pass # Raise any exception here if ``value`` is invalid.
17
18 Validation happens **after** the data converter runs.
19 Any of :exc:`AssertionError`, :exc:`TypeError` or :exc:`ValidationError` will be promoted to a :exc:`cyclopts.ValidationError` so that the exception gets presented to the end-user in a nicer way.
20 More than one validator can be supplied as a list to the :attr:`~.Parameter.validator` field.
21
22 Cyclopts has some builtin common validators in the :ref:`cyclopts.validators <API Validators>` module.
23 See :ref:`Annotated Types` for common specific definitions provided as convenient pre-annotated types.
24
25 ----
26 Path
27 ----
28 The :class:`.Path` validator ensures certain properties
29 of the parsed :class:`pathlib.Path` object, such as asserting the file must exist.
30
31 .. code-block:: python
32
33 from cyclopts import App, Parameter, validators
34 from typing import Annotated
35 from pathlib import Path
36
37 app = App()
38
39 @app.default()
40 def foo(path: Annotated[Path, Parameter(validator=validators.Path(exists=True))]):
41 print(f"File contents:\n{path.read_text()}")
42
43 app()
44
45 .. code-block:: console
46
47 $ echo Hello World > my_file.txt
48
49 $ my-script my_file.txt
50 File contents:
51 Hello World
52
53 $ my-script this_file_does_not_exist.txt
54 ╭─ Error ────────────────────────────────────────────────────────────╮
55 │ Invalid value "this_file_does_not_exist.txt" for "PATH". │
56 │ "this_file_does_not_exist.txt" does not exist. │
57 ╰────────────────────────────────────────────────────────────────────╯
58
59 See :ref:`Annotated Path Types <Annotated Path Types>` for Annotated-Type equivalents of common Path converter/validators.
60
61 ------
62 Number
63 ------
64 The :class:`.Number` validator can set minimum and maximum input values.
65
66 .. code-block:: python
67
68 from cyclopts import App, Parameter, validators
69 from typing import Annotated
70
71 app = App()
72
73 @app.default()
74 def foo(n: Annotated[int, Parameter(validator=validators.Number(gte=0, lt=16))]):
75 print(f"Your number in hex is {str(hex(n))[2]}.")
76
77 app()
78
79 .. code-block:: console
80
81 $ my-script 0
82 Your number in hex is 0.
83
84 $ my-script 15
85 Your number in hex is f.
86
87 $ my-script 16
88 ╭─ Error ────────────────────────────────────────────────────────────╮
89 │ Invalid value "16" for "N". Must be < 16. │
90 ╰────────────────────────────────────────────────────────────────────╯
91
92 See :ref:`Annotated Number Types <Annotated Number Types>` for Annotated-Type equivalents of common Number converter/validators.