0
# Arguments and Parameters
1
2
Fine-grained control over command-line argument behavior, validation, and presentation through Argument, Parameter, and related configuration classes.
3
4
## Capabilities
5
6
### Argument Class
7
8
Represents a command-line argument with type information and metadata.
9
10
```python { .api }
11
class Argument:
12
def __init__(
13
self,
14
*,
15
converter: Callable | None = None,
16
validator: Callable | list[Callable] | None = None,
17
default: Any = UNSET,
18
default_factory: Callable[[], Any] | None = None,
19
help: str | None = None,
20
show: bool = True,
21
group: Group | None = None,
22
**kwargs
23
):
24
"""
25
Create an argument specification.
26
27
Parameters
28
----------
29
converter
30
Function to convert string tokens to target type
31
validator
32
Function or list of functions to validate converted value
33
default
34
Default value if argument not provided
35
default_factory
36
Factory function to generate default value
37
help
38
Help text for this argument
39
show
40
Whether to show this argument in help
41
group
42
Group for organizing this argument in help display
43
"""
44
```
45
46
### ArgumentCollection Class
47
48
List-like collection of Argument objects with validation.
49
50
```python { .api }
51
class ArgumentCollection(list):
52
def __init__(self, *args: Argument):
53
"""
54
Create a collection of arguments.
55
56
Parameters
57
----------
58
args
59
Argument objects to include in collection
60
"""
61
62
def append(self, argument: Argument) -> None:
63
"""
64
Add an argument to the collection.
65
66
Parameters
67
----------
68
argument
69
Argument to add
70
"""
71
72
def __getitem__(self, index: int) -> Argument:
73
"""Get argument by index."""
74
75
def __len__(self) -> int:
76
"""Get number of arguments in collection."""
77
```
78
79
### Parameter Class
80
81
Configuration class for command parameters with advanced options.
82
83
```python { .api }
84
class Parameter:
85
def __init__(
86
self,
87
*names: str,
88
converter: Callable | None = None,
89
validator: Callable | list[Callable] | None = None,
90
default: Any = UNSET,
91
default_factory: Callable[[], Any] | None = None,
92
help: str | None = None,
93
show: bool = True,
94
group: Group | None = None,
95
env_var: str | Iterable[str] | None = None,
96
negative: str | Iterable[str] | None = None,
97
**kwargs
98
):
99
"""
100
Create a parameter specification.
101
102
Parameters
103
----------
104
names
105
Parameter names (e.g., "--verbose", "-v")
106
converter
107
Function to convert string tokens to target type
108
validator
109
Function or list of functions to validate converted value
110
default
111
Default value if parameter not provided
112
default_factory
113
Factory function to generate default value
114
help
115
Help text for this parameter
116
show
117
Whether to show this parameter in help
118
group
119
Group for organizing this parameter in help display
120
env_var
121
Environment variable names to check for value
122
negative
123
Negative flag names for boolean parameters
124
"""
125
```
126
127
### Group Class
128
129
Organizational structure for commands and parameters in help display.
130
131
```python { .api }
132
@dataclass(frozen=True)
133
class Group:
134
name: str
135
title: str = ""
136
description: str = ""
137
panel: Panel | None = None
138
sort_key: Callable[[str], Any] | None = None
139
default_parameter: Parameter | None = None
140
141
def __init__(
142
self,
143
name: str,
144
title: str = "",
145
description: str = "",
146
panel: Panel | None = None,
147
sort_key: Callable[[str], Any] | None = None,
148
default_parameter: Parameter | None = None
149
):
150
"""
151
Create a group for organizing CLI elements.
152
153
Parameters
154
----------
155
name
156
Internal name for the group
157
title
158
Display title for the group
159
description
160
Description text for the group
161
panel
162
Rich panel configuration for display
163
sort_key
164
Function for sorting elements within group
165
default_parameter
166
Default parameter configuration for group members
167
"""
168
```
169
170
### Token Class
171
172
Immutable representation of user input with parsing context.
173
174
```python { .api }
175
class Token:
176
keyword: str
177
value: str
178
source: str
179
index: int
180
keys: tuple[str, ...]
181
implicit_value: str | None
182
183
def __init__(
184
self,
185
keyword: str,
186
value: str,
187
source: str = "unknown",
188
index: int = 0,
189
keys: tuple[str, ...] = (),
190
implicit_value: str | None = None
191
):
192
"""
193
Create a token representing user input.
194
195
Parameters
196
----------
197
keyword
198
The option keyword (e.g., "--verbose")
199
value
200
The string value provided
201
source
202
Source of the token (e.g., "cli", "env", "config")
203
index
204
Position index in the input sequence
205
keys
206
Nested keys for structured configuration
207
implicit_value
208
Implicit value for flag-style options
209
"""
210
211
def __str__(self) -> str:
212
"""String representation of the token."""
213
214
def __repr__(self) -> str:
215
"""Detailed representation of the token."""
216
```
217
218
### Utility Constants and Functions
219
220
Core utilities for argument handling.
221
222
```python { .api }
223
UNSET: object
224
"""Sentinel value indicating no data provided."""
225
226
def default_name_transform(name: str) -> str:
227
"""
228
Convert Python identifier to CLI token format.
229
230
Parameters
231
----------
232
name
233
Python identifier (e.g., "my_parameter")
234
235
Returns
236
-------
237
str
238
CLI token format (e.g., "--my-parameter")
239
"""
240
```
241
242
## Usage Examples
243
244
### Basic Parameter Configuration
245
246
```python
247
from cyclopts import App, Parameter
248
249
app = App()
250
251
@app.command
252
def process(
253
input_file: str,
254
output_file: str = Parameter(help="Output file path"),
255
verbose: bool = Parameter("--verbose", "-v", help="Enable verbose output"),
256
count: int = Parameter(default=10, help="Number of iterations")
257
):
258
"""Process files with configurable options."""
259
if verbose:
260
print(f"Processing {input_file} -> {output_file}, {count} iterations")
261
```
262
263
### Advanced Parameter with Validation
264
265
```python
266
from cyclopts import App, Parameter
267
from cyclopts.validators import Number
268
from pathlib import Path
269
270
app = App()
271
272
@app.command
273
def analyze(
274
data_file: Path = Parameter(help="Input data file"),
275
threshold: float = Parameter(
276
default=0.5,
277
validator=Number(min=0.0, max=1.0),
278
help="Analysis threshold (0.0-1.0)"
279
),
280
output_dir: Path = Parameter(
281
default_factory=lambda: Path.cwd() / "output",
282
help="Output directory"
283
)
284
):
285
"""Analyze data with validated parameters."""
286
print(f"Analyzing {data_file} with threshold {threshold}")
287
print(f"Output will be saved to {output_dir}")
288
```
289
290
### Grouped Parameters
291
292
```python
293
from cyclopts import App, Parameter, Group
294
295
# Define groups
296
input_group = Group("input", "Input Options", "Configure input sources")
297
output_group = Group("output", "Output Options", "Configure output formatting")
298
299
app = App()
300
301
@app.command
302
def convert(
303
input_file: str = Parameter(group=input_group, help="Input file"),
304
input_format: str = Parameter(group=input_group, help="Input format"),
305
output_file: str = Parameter(group=output_group, help="Output file"),
306
output_format: str = Parameter(group=output_group, help="Output format")
307
):
308
"""Convert files between formats."""
309
print(f"Converting {input_file} ({input_format}) -> {output_file} ({output_format})")
310
```
311
312
### Environment Variable Integration
313
314
```python
315
from cyclopts import App, Parameter
316
317
app = App()
318
319
@app.command
320
def deploy(
321
service: str,
322
region: str = Parameter(
323
env_var="AWS_REGION",
324
default="us-east-1",
325
help="AWS region for deployment"
326
),
327
api_key: str = Parameter(
328
env_var=["API_KEY", "SERVICE_API_KEY"],
329
help="API key for authentication"
330
)
331
):
332
"""Deploy service with environment variable support."""
333
print(f"Deploying {service} to {region}")
334
```