Debian Codegraph @

docs/source/cookbook/dataclass_commands.rst

raw
1 .. _Dataclass Commands:
2
3 ==================
4 Dataclass Commands
5 ==================
6
7 An alternative command syntax is to use dataclasses with a ``__call__`` method.
8 To support this pattern, Cyclopts provides the ``"call_if_callable"`` result action,
9 which can be composed with other result actions.
10
11 Basic Example
12 =============
13
14 Here's a simple example using the dataclass command pattern:
15
16 .. code-block:: python
17
18 # greeter.py
19 from dataclasses import dataclass, KW_ONLY
20 from cyclopts import App
21
22 app = App(result_action=["call_if_callable", "print_non_int_sys_exit"])
23
24 @app.command
25 @dataclass
26 class Greet:
27 """Greet someone with a message."""
28
29 name: str = "World"
30 _: KW_ONLY
31 formal: bool = False
32
33 def __call__(self):
34 greeting = "Hello" if self.formal else "Hey"
35 return f"{greeting} {self.name}."
36
37 if __name__ == "__main__":
38 app()
39
40 Running this application:
41
42 .. code-block:: console
43
44 $ python greeter.py greet
45 Hey World.
46
47 $ python greeter.py greet Alice
48 Hey Alice.
49
50 $ python greeter.py greet Bob --formal
51 Hello Bob.
52
53 How It Works
54 ============
55
56 The ``result_action=["call_if_callable", "print_non_int_sys_exit"]`` creates a pipeline:
57
58 1. **call_if_callable**: After parsing, Cyclopts creates an instance of the ``Greet`` dataclass.
59 This action checks if the result is callable (it is, because of ``__call__``), and calls it with no arguments.
60
61 2. **print_non_int_sys_exit**: Takes the string returned by ``__call__`` and prints it, then exits.
62
63 Without ``"call_if_callable"``, the app would try to print the dataclass instance itself
64 instead of calling it and printing the result.