Debian Codegraph @

docs/source/default_parameter.rst

raw
1 .. _Default Parameter:
2
3 =================
4 Default Parameter
5 =================
6 The default values of :class:`.Parameter` for an app can be configured via :attr:`.App.default_parameter`.
7
8 For example, to disable the :attr:`~.Parameter.negative` flag feature across your entire app:
9
10 .. code-block:: python
11
12 from cyclopts import App, Parameter
13
14 app = App(default_parameter=Parameter(negative=()))
15
16 @app.command
17 def foo(*, flag: bool):
18 pass
19
20 app()
21
22 Consequently, ``--no-flag`` is no longer an allowed flag:
23
24 .. code-block:: console
25
26 $ my-script foo --help
27 Usage: my-script foo [ARGS] [OPTIONS]
28
29 ╭─ Parameters ──────────────────────────────────────────────────╮
30 │ * --flag [required] │
31 ╰───────────────────────────────────────────────────────────────╯
32
33 Explicitly annotating the parameter with :attr:`~.Parameter.negative` overrides this configuration and works as expected:
34
35
36 .. code-block:: python
37
38 from cyclopts import App, Parameter
39 from typing import Annotated
40
41 app = App(default_parameter=Parameter(negative=()))
42
43 @app.command
44 def foo(*, flag: Annotated[bool, Parameter(negative="--anti-flag")]):
45 pass
46
47 app()
48
49 .. code-block:: console
50
51 $ my-script foo --help
52 Usage: my-script foo [ARGS] [OPTIONS]
53
54 ╭─ Parameters ──────────────────────────────────────────────────╮
55 │ * --flag --anti-flag [required] │
56 ╰───────────────────────────────────────────────────────────────╯
57
58 .. _Parameter Resolution Order:
59
60 ----------------
61 Resolution Order
62 ----------------
63
64 When resolving what the :class:`.Parameter` values for an individual function parameter should be, explicitly set attributes of higher priority :class:`.Parameter` s override lower priority :class:`.Parameter` s. The resolution order is as follows:
65
66 1. **Highest Priority:** Parameter-annotated command function signature ``Annotated[..., Parameter()]``.
67
68 2. :attr:`.Group.default_parameter` that the **parameter** belongs to.
69
70 3. :attr:`.App.default_parameter` of the **app** that registered the command.
71
72 4. :attr:`.Group.default_parameter` of the **app** that the function belongs to.
73
74 5. **Lowest Priority:** (2-4) recursively of the parenting app call-chain.
75
76 Any of Parameter's fields can be set to `None` to revert back to the true-original Cyclopts default.
77
78 .. _Skipping Private Parameters:
79
80 ---------------------------
81 Skipping Private Parameters
82 ---------------------------
83
84 The :attr:`.Parameter.parse` attribute can accept a **regex pattern** to selectively skip parameters based on their name.
85 This is useful for defining "private" parameters that are externally injected (e.g. a :ref:`Meta App`, dependency-injection framework, etc) rather than parsed from the CLI.
86
87 For example, to skip all underscore-prefixed parameters:
88
89 .. code-block:: python
90
91 from typing import Annotated
92 from cyclopts import App, Parameter
93
94 # The regex "^(?!_)" matches names that do NOT start with underscore.
95 app = App(default_parameter=Parameter(parse="^(?!_)"))
96
97 @app.command
98 def greet(name: str, *, _db: Database):
99 user = _db.get_user(name)
100 print(f"Hello {user.full_name}!")
101
102 @app.meta.default
103 def launcher(*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)]):
104 # Create shared resources
105 db = Database("myapp.db")
106
107 # Parse CLI and get ignored (non-parsed) parameters
108 command, bound, ignored = app.parse_args(tokens)
109
110 # Inject ignored parameters
111 for name, type_ in ignored.items():
112 if type_ is Database:
113 bound.kwargs[name] = db
114
115 return command(*bound.args, **bound.kwargs)
116
117 if __name__ == "__main__":
118 app.meta()
119
120 .. code-block:: console
121
122 $ my-script --help
123 Usage: my-script COMMAND
124
125 ╭─ Commands ────────────────────────────────────────────────────╮
126 │ greet │
127 │ --help,-h Display this message and exit. │
128 │ --version Display application version. │
129 ╰───────────────────────────────────────────────────────────────╯
130
131 $ my-script greet --help
132 Usage: my-script greet [ARGS] [OPTIONS]
133
134 ╭─ Parameters ──────────────────────────────────────────────────╮
135 │ * NAME,--name [required] │
136 ╰───────────────────────────────────────────────────────────────╯
137
138 Notice that ``_db`` does not appear in the help screen.
139 Parameters that don't match the regex pattern are added to the ``ignored`` dictionary returned by :meth:`.App.parse_args`, making them available for meta-app injection.
140
141 Like all other :class:`Parameter` configurations, explicitly annotating with ``parse=True`` overrides the app-level regex:
142
143 .. code-block:: python
144
145 from typing import Annotated
146 from cyclopts import App, Parameter
147
148 app = App(default_parameter=Parameter(parse="^(?!_)"))
149
150 @app.default
151 def main(name: str, *, _verbose: Annotated[bool, Parameter(parse=True)] = False):
152 """_verbose IS parsed despite the underscore prefix"""
153
154 .. important::
155
156 Parameters that are not parsed (either via ``parse=False`` or a non-matching regex pattern) **must** be either:
157
158 * Keyword-only (defined after ``*`` in the function signature), or
159 * Have a default value
160
161 .. code-block:: python
162
163 # Valid: keyword-only parameter
164 def main(*, _context: dict): ...
165
166 # Valid: has default value
167 def main(_context: dict = None): ...
168
169 # Invalid: positional without default - raises ValueError
170 def main(_context: dict): ...