Debian Codegraph @

docs/source/meta_app.rst

raw
1 .. _Meta App:
2
3 ========
4 Meta App
5 ========
6 What if you want more control over the application launch process?
7 Cyclopts provides the option of launching an app from an app; a meta app!
8
9 ------------
10 Meta Sub App
11 ------------
12 Typically, a Cyclopts application is launched by calling the :class:`.App` object:
13
14 .. code-block:: python
15
16 from cyclopts import App
17
18 app = App()
19 # Register some commands here (not shown)
20 app() # Run the app
21
22 To change how the primary app is run, you can use the meta-app feature of Cyclopts.
23 The meta app is a special :class:`.App` that inherits configuration from its parent
24 and has its help-page merged with the parent app's help.
25
26 .. code-block:: python
27
28 from cyclopts import App, Group, Parameter
29 from typing import Annotated
30
31 app = App()
32 # Rename the meta's "Parameter" -> "Session Parameters".
33 # Set sort_key so it will be drawn higher up the help-page.
34 app.meta.group_parameters = Group("Session Parameters", sort_key=0)
35
36 @app.command
37 def foo(loops: int):
38 for i in range(loops):
39 print(f"Looping! {i}")
40
41 @app.meta.default
42 def my_app_launcher(*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)], user: str):
43 print(f"Hello {user}")
44 app(tokens)
45
46 app.meta()
47
48 .. code-block:: console
49
50 $ my-script --user=Bob foo 3
51 Hello Bob
52 Looping! 0
53 Looping! 1
54 Looping! 2
55
56 The variable positional ``*tokens`` will aggregate all remaining tokens, including those starting with a hyphen (typically options).
57 We can then pass them along to the primary ``app``.
58
59 The ``meta`` app inherits many configuration values from its parent app and is
60 additionally scanned when generating help screens.
61 ``*tokens`` is annotated with ``show=False`` since we do not want this variable to show up in the help screen.
62
63 .. code-block:: console
64
65 $ my-script --help
66 Usage: my-script COMMAND
67
68 ╭─ Session Parameters ────────────────────────────────────────────────────╮
69 │ * --user [required] │
70 ╰─────────────────────────────────────────────────────────────────────────╯
71 ╭─ Commands ──────────────────────────────────────────────────────────────╮
72 │ foo │
73 │ --help,-h Display this message and exit. │
74 │ --version Display application version. │
75 ╰─────────────────────────────────────────────────────────────────────────╯
76
77 -------------
78 Meta Commands
79 -------------
80 If you want a command to circumvent ``my_app_launcher``, add it as you would any other command to the meta app.
81
82 .. code-block:: python
83
84 @app.meta.command
85 def info():
86 print("CLI didn't have to provide --user to call this.")
87
88 .. code-block:: console
89
90 $ my-script info
91 CLI didn't have to provide --user to call this.
92
93 $ my-script --help
94 Usage: my-script COMMAND
95
96 ╭─ Session Parameters ────────────────────────────────────────────────────╮
97 │ * --user [required] │
98 ╰─────────────────────────────────────────────────────────────────────────╯
99 ╭─ Commands ──────────────────────────────────────────────────────────────╮
100 │ foo │
101 │ info │
102 │ --help,-h Display this message and exit. │
103 │ --version Display application version. │
104 ╰─────────────────────────────────────────────────────────────────────────╯
105
106 Just like a standard application, the parsed ``command`` executes instead of ``default``.
107
108 -------------------------
109 Custom Command Invocation
110 -------------------------
111 The core logic of :meth:`.App.__call__` method is the following:
112
113 .. code-block:: python
114
115 def __call__(self, tokens=None, **kwargs):
116 command, bound, ignored = self.parse_args(tokens, **kwargs)
117 return command(*bound.args, **bound.kwargs)
118
119 Knowing this, we can easily customize how we actually invoke actions with Cyclopts.
120 Let's imagine that we want to instantiate an object, ``User`` in our meta app, and pass it to subsequent commands that need it.
121 This might be useful to share an expensive-to-create object amongst commands in a single session; see :ref:`Command Chaining`.
122
123 .. code-block:: python
124
125 from cyclopts import App, Parameter
126 from typing import Annotated
127
128 app = App()
129
130 class User:
131 def __init__(self, name):
132 self.name = name
133
134 @app.command
135 def create(
136 age: int,
137 *,
138 user_obj: Annotated[User, Parameter(parse=False)],
139 ):
140 print(f"Creating user {user_obj.name} with age {age}.")
141
142 @app.meta.default
143 def launcher(*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)], user: str):
144 additional_kwargs = {}
145 command, bound, ignored = app.parse_args(tokens)
146 # "ignored" is a dict mapping python-variable-name to it's type annotation for parameters with "parse=False".
147 if "user_obj" in ignored:
148 # 'ignored["user_obj"]' is the class "User"
149 additional_kwargs["user_obj"] = ignored["user_obj"](user)
150 return command(*bound.args, **bound.kwargs, **additional_kwargs)
151
152 if __name__ == "__main__":
153 app.meta()
154
155 .. code-block:: console
156
157 $ my-script create --user Alice 30
158 Creating user Alice with age 30.
159
160 The ``parse=False`` configuration tells Cyclopts to not try and bind arguments to this parameter.
161 Cyclopts will pass it along to ``ignored`` to make custom meta-app logic easier.
162 The annotated parameter **must** be a keyword-only parameter.
163
164 .. tip::
165
166 For app-wide control over which parameters are parsed, :attr:`~.Parameter.parse` can also accept a **regex pattern**.
167 This can be useful for automatically skipping all "private" parameters (e.g., those prefixed with ``_``) with the regex pattern ``"^(?!_)"``.
168 See :ref:`Skipping Private Parameters` for details.