Debian Codegraph @

docs/source/user_classes.rst

raw
1 ============
2 User Classes
3 ============
4 Cyclopts supports classically defined user classes, as well as classes defined by the following dataclass-like libraries:
5
6 * `attrs <https://www.attrs.org/en/stable/>`_
7 * `dataclass <https://docs.python.org/3/library/dataclasses.html>`_
8 * `pydantic <https://docs.pydantic.dev/latest/>`_
9 * `NamedTuple <https://docs.python.org/3/library/typing.html#typing.NamedTuple>`_
10 * `TypedDict <https://docs.python.org/3/library/typing.html#typing.TypedDict>`_
11
12 Basic Example
13 ^^^^^^^^^^^^^
14 As an example, let's consider using the builtin :obj:`~dataclasses.dataclass` to make a CLI that manages a movie collection.
15
16 .. code-block:: python
17
18 from cyclopts import App
19 from dataclasses import dataclass
20
21 app = App(name="movie-maintainer")
22
23 @dataclass
24 class Movie:
25 title: str
26 year: int
27
28 @app.command
29 def add(movie: Movie):
30 print(f"Adding movie: {movie}")
31
32 app()
33
34 .. code-block:: console
35
36 $ movie-maintainer add --help
37 Usage: movie-maintainer add [ARGS] [OPTIONS]
38
39 ╭─ Parameters ────────────────────────────────────────────────╮
40 │ * MOVIE.TITLE [required] │
41 │ --movie.title │
42 │ * MOVIE.YEAR --movie.year [required] │
43 ╰─────────────────────────────────────────────────────────────╯
44
45 $ movie-maintainer add 'Mad Max: Fury Road' 2015
46 Adding movie: Movie(title='Mad Max: Fury Road', year=2015)
47
48 $ movie-maintainer add --movie.title 'Furiosa: A Mad Max Saga' --movie.year 2024
49 Adding movie: Movie(title='Furiosa: A Mad Max Saga', year=2024)
50
51 In most circumstances, Cyclopts will also parse a json-string for a dataclass-like parameter:
52
53 .. code-block:: console
54
55 $ movie-maintainer add --movie='{"title": "Mad Max: Fury Road", "year": 2024}'
56 Adding movie: Movie(title='Mad Max: Fury Road', year=2024)
57
58 JSON Dict Parsing
59 ^^^^^^^^^^^^^^^^^
60
61 JSON dict parsing will be performed when:
62
63 1. The parameter is specified as a keyword option; e.g. ``--movie``.
64 2. The referenced parameter type has various sub-arguments (is dataclass-like).
65 3. The referenced parameter is **not** union'd with a ``str``.
66 4. The first character is a ``{``.
67
68 This behavior can be configured via :attr:`.Parameter.json_dict`.
69
70 .. code-block:: python
71
72 from cyclopts import App
73 from dataclasses import dataclass
74
75 app = App(name="movie-manager")
76
77 @dataclass
78 class Movie:
79 title: str
80 year: int
81 rating: float = 8.0
82
83 @app.command
84 def add(movie: Movie):
85 print(f"Adding: {movie}")
86
87 app()
88
89 .. code-block:: console
90
91 $ movie-manager add --movie '{"title": "Mad Max: Fury Road", "year": 2015, "rating": 8.1}'
92 Adding: Movie(title='Mad Max: Fury Road', year=2015, rating=8.1)
93
94 $ movie-manager add --movie '{"title": "Furiosa", "year": 2024}'
95 Adding: Movie(title='Furiosa', year=2024, rating=8.0)
96
97 Note that JSON parsing only works when using the keyword option format (``--movie``). The traditional positional argument format still works with individual fields:
98
99 .. code-block:: console
100
101 $ movie-manager add --movie.title "Dune" --movie.year 2021 --movie.rating 8.5
102 Adding: Movie(title='Dune', year=2021, rating=8.5)
103
104 JSON List Parsing
105 ^^^^^^^^^^^^^^^^^
106
107 Cyclopts also supports JSON parsing for lists of dataclasses. This allows you to pass multiple structured objects via JSON:
108
109 .. code-block:: python
110
111 from cyclopts import App
112 from dataclasses import dataclass
113
114 app = App(name="movie-collection")
115
116 @dataclass
117 class Movie:
118 title: str
119 year: int
120
121 @app.command
122 def add_batch(movies: list[Movie]):
123 for movie in movies:
124 print(f"Adding: {movie}")
125
126 app()
127
128 You can provide the list in several ways:
129
130 1. JSON Array - Multiple objects in a single argument:
131
132 .. code-block:: console
133
134 $ movie-collection add-batch --movies '[{"title": "Mad Max", "year": 2015}, {"title": "Furiosa", "year": 2024}]'
135 Adding: Movie(title='Mad Max', year=2015)
136 Adding: Movie(title='Furiosa', year=2024)
137
138 2. Individual JSON - Each object as a separate argument:
139
140 .. code-block:: console
141
142 $ movie-collection add-batch --movies '{"title": "Mad Max", "year": 2015}' --movies '{"title": "Furiosa", "year": 2024}'
143 Adding: Movie(title='Mad Max', year=2015)
144 Adding: Movie(title='Furiosa', year=2024)
145
146 3. Mixed - Combining arrays and individual objects:
147
148 .. code-block:: console
149
150 $ movie-collection add-batch --movies '{"title": "Mad Max", "year": 2015}' --movies '[{"title": "Furiosa", "year": 2024}, {"title": "Dune", "year": 2021}]'
151 Adding: Movie(title='Mad Max', year=2015)
152 Adding: Movie(title='Furiosa', year=2024)
153 Adding: Movie(title='Dune', year=2021)
154
155 JSON list parsing is automatically enabled for ``list`` types containing dataclasses. The same rules apply as for dict parsing:
156
157 - The element type cannot be union'd with ``str``
158 - JSON objects must start with ``{`` or be arrays starting with ``[``
159
160 This behavior can be configured via :attr:`.Parameter.json_list`.
161
162 .. _Namespace Flattening:
163
164 Namespace Flattening
165 ^^^^^^^^^^^^^^^^^^^^
166
167 It is likely that the actual movie class/object is not important to the CLI user, and the parameter names like ``--movie.title`` are unnecessarily verbose. We can remove ``movie`` from the name by giving the ``Movie`` type annotation the special name ``"*"``.
168
169 .. code-block:: python
170
171 from cyclopts import App, Parameter
172 from dataclasses import dataclass
173 from typing import Annotated
174
175 app = App(name="movie-maintainer")
176
177 @dataclass
178 class Movie:
179 title: str
180 year: int
181
182 @app.command
183 def add(movie: Annotated[Movie, Parameter(name="*")]):
184 print(f"Adding movie: {movie}")
185
186 app()
187
188 .. code-block:: console
189
190 $ movie-maintainer add --help
191 Usage: movie-maintainer add [ARGS] [OPTIONS]
192
193 ╭─ Parameters ────────────────────────────────────────────────╮
194 │ * TITLE --title [required] │
195 │ * YEAR --year [required] │
196 ╰─────────────────────────────────────────────────────────────╯
197
198 An alternative way of supplying the :class:`.Parameter` configuration is via a decorator.
199 This way can be cleaner and terser in many scenarios.
200 The :class:`.Parameter` configuration will also be inherited by subclasses.
201
202 .. code-block:: python
203
204 from cyclopts import App, Parameter
205 from dataclasses import dataclass
206
207 app = App(name="movie-maintainer")
208
209 @Parameter(name="*")
210 @dataclass
211 class Movie:
212 title: str
213 year: int
214
215 @app.command
216 def add(movie: Movie):
217 print(f"Adding movie: {movie}")
218
219 app()
220
221 .. _Sharing Parameters:
222
223 Sharing Parameters
224 ^^^^^^^^^^^^^^^^^^
225 A flattened dataclass provides a natural way of easily sharing a set of parameters between commands.
226
227 .. code-block:: python
228
229 from cyclopts import App, Parameter
230 from dataclasses import dataclass
231
232 app = App(name="movie-maintainer")
233
234 @Parameter(name="*")
235 @dataclass
236 class Config:
237 user: str
238 server: str = "media.sqlite"
239
240 @dataclass
241 class Movie:
242 title: str
243 year: int
244
245 @app.command
246 def add(movie: Movie, *, config: Config):
247 print(f"Config: {config}")
248 print(f"Adding movie: {movie}")
249
250 @app.command
251 def remove(movie: Movie, *, config: Config):
252 print(f"Config: {config}")
253 print(f"Removing movie: {movie}")
254
255 app()
256
257 .. code-block:: console
258
259 $ movie-maintainer remove --help
260 Usage: movie-maintainer remove [ARGS] [OPTIONS]
261
262 ╭─ Parameters ────────────────────────────────────────────────╮
263 │ * MOVIE.TITLE [required] │
264 │ --movie.title │
265 │ * MOVIE.YEAR --movie.year [required] │
266 │ * --user [required] │
267 │ --server [default: media.sqlite] │
268 ╰─────────────────────────────────────────────────────────────╯
269
270 $ movie-maintainer remove 'Mad Max: Fury Road' 2015 --user Guido
271 Config: Config(user='Guido', server='media.sqlite')
272 Removing movie: Movie(title='Mad Max: Fury Road', year=2015)
273
274
275 Config File
276 ^^^^^^^^^^^
277 Having the user specify ``--user`` every single call is a bit cumbersome, especially if they're always going to provide the same value.
278 We can have Cyclopts fallback to a :ref:`toml configuration file <Config Files>`.
279
280 Consider the following toml data saved to ``config.toml``:
281
282 .. code-block:: toml
283
284 # config.toml
285 user = "Guido"
286
287 We can update our app to fill in missing CLI parameters from this file:
288
289 .. code-block:: python
290
291 from cyclopts import App, Parameter, config
292 from dataclasses import dataclass
293 from typing import Annotated
294
295 app = App(
296 name="movie-maintainer",
297 config=config.Toml("config.toml", use_commands_as_keys=False),
298 )
299
300 @Parameter(name="*")
301 @dataclass
302 class Config:
303 user: str
304 server: str = "media.sqlite"
305
306 @dataclass
307 class Movie:
308 title: str
309 year: int
310
311 @app.command
312 def add(movie: Movie, *, config: Config):
313 print(f"Config: {config}")
314 print(f"Adding movie: {movie}")
315
316 app()
317
318 .. code-block:: console
319
320 $ movie-maintainer add 'Mad Max: Fury Road' 2015
321 Config: Config(user='Guido', server='media.sqlite')
322 Adding movie: Movie(title='Mad Max: Fury Road', year=2015)