0
# Core Parser Functionality
1
2
The ArgumentParser class serves as the foundation of jsonargparse, extending Python's argparse.ArgumentParser with support for configuration files, environment variables, advanced type handling, and nested configurations. It provides the core parsing and validation capabilities that power all other jsonargparse features.
3
4
## Capabilities
5
6
### ArgumentParser Class
7
8
The main parser class that handles argument parsing from multiple sources including command line, configuration files, and environment variables.
9
10
```python { .api }
11
class ArgumentParser:
12
def __init__(self,
13
prog: Optional[str] = None,
14
usage: Optional[str] = None,
15
description: Optional[str] = None,
16
epilog: Optional[str] = None,
17
formatter_class: Type = DefaultHelpFormatter,
18
prefix_chars: str = "-",
19
fromfile_prefix_chars: Optional[str] = None,
20
argument_default: Any = None,
21
conflict_handler: str = "error",
22
add_help: bool = True,
23
allow_abbrev: bool = True,
24
exit_on_error: bool = True,
25
env_prefix: Union[bool, str] = True,
26
logger: Union[bool, str, dict, logging.Logger] = False,
27
version: Optional[str] = None,
28
print_config: Optional[str] = "--print_config",
29
parser_mode: str = "yaml",
30
dump_header: Optional[List[str]] = None,
31
default_config_files: Optional[List[Union[str, os.PathLike]]] = None,
32
default_env: bool = False,
33
default_meta: bool = True,
34
**kwargs
35
):
36
"""
37
Create a new argument parser.
38
39
Args:
40
env_prefix: Prefix for environment variables (True for prog name)
41
logger: Logger configuration for the parser
42
version: Version string to display with --version
43
print_config: Option name for printing current config
44
parser_mode: Default parsing mode ('yaml', 'json', etc.)
45
default_config_files: List of default config file paths
46
default_env: Whether to parse environment variables by default
47
default_meta: Whether to include metadata in parsed configs
48
"""
49
```
50
51
### Parsing Methods
52
53
Core methods for parsing arguments from different sources with comprehensive configuration merging.
54
55
```python { .api }
56
def parse_args(self, args: Optional[List[str]] = None, namespace: Optional[Namespace] = None) -> Namespace:
57
"""
58
Parse command line arguments, config files, and environment variables.
59
60
Args:
61
args: List of arguments to parse (defaults to sys.argv)
62
namespace: Namespace object to populate
63
64
Returns:
65
Namespace: Parsed configuration namespace
66
"""
67
68
def parse_object(self, cfg_obj: Any, cfg_path: str = "") -> Namespace:
69
"""
70
Parse configuration from a nested object (dict, namespace, etc.).
71
72
Args:
73
cfg_obj: Configuration object to parse
74
cfg_path: Path identifier for error messages
75
76
Returns:
77
Namespace: Parsed configuration namespace
78
"""
79
80
def parse_path(self, cfg_path: Union[str, os.PathLike], ext_vars: Optional[Dict[str, str]] = None) -> Namespace:
81
"""
82
Parse configuration from a file path.
83
84
Args:
85
cfg_path: Path to configuration file
86
ext_vars: External variables for jsonnet files
87
88
Returns:
89
Namespace: Parsed configuration namespace
90
"""
91
92
def parse_string(self, cfg_str: str, cfg_path: str = "", ext_vars: Optional[Dict[str, str]] = None) -> Namespace:
93
"""
94
Parse configuration from a string.
95
96
Args:
97
cfg_str: Configuration string to parse
98
cfg_path: Path identifier for error messages
99
ext_vars: External variables for jsonnet strings
100
101
Returns:
102
Namespace: Parsed configuration namespace
103
"""
104
105
def parse_env(self, env: Optional[Dict[str, str]] = None, defaults: bool = True) -> Namespace:
106
"""
107
Parse configuration from environment variables.
108
109
Args:
110
env: Environment variables dict (defaults to os.environ)
111
defaults: Whether to include default values
112
113
Returns:
114
Namespace: Parsed configuration namespace
115
"""
116
```
117
118
### Configuration Output Methods
119
120
Methods for serializing and saving parsed configurations in various formats.
121
122
```python { .api }
123
def dump(self, cfg: Optional[Namespace] = None, format: Optional[str] = None, **kwargs) -> str:
124
"""
125
Generate configuration string from namespace.
126
127
Args:
128
cfg: Configuration namespace to dump
129
format: Output format ('yaml', 'json', etc.)
130
131
Returns:
132
str: Serialized configuration string
133
"""
134
135
def save(self, cfg: Namespace, path: Union[str, os.PathLike], format: Optional[str] = None, **kwargs) -> None:
136
"""
137
Save configuration to file.
138
139
Args:
140
cfg: Configuration namespace to save
141
path: Output file path
142
format: Output format (inferred from extension if not provided)
143
"""
144
```
145
146
### Configuration Management
147
148
Methods for handling default values, merging configurations, and managing parser state.
149
150
```python { .api }
151
def get_defaults(self) -> Namespace:
152
"""
153
Get default values for all arguments.
154
155
Returns:
156
Namespace: Default configuration values
157
"""
158
159
def set_defaults(self, **kwargs) -> None:
160
"""
161
Set default values for arguments.
162
163
Args:
164
**kwargs: Argument names and their default values
165
"""
166
167
def merge_config(self, cfg_from: Namespace, cfg_to: Namespace) -> Namespace:
168
"""
169
Merge two configuration namespaces.
170
171
Args:
172
cfg_from: Source configuration namespace
173
cfg_to: Target configuration namespace
174
175
Returns:
176
Namespace: Merged configuration namespace
177
"""
178
```
179
180
### Validation and Processing
181
182
Methods for validating configurations and processing parsed values.
183
184
```python { .api }
185
def validate(self, cfg: Namespace) -> Namespace:
186
"""
187
Validate a configuration namespace.
188
189
Args:
190
cfg: Configuration namespace to validate
191
192
Returns:
193
Namespace: Validated configuration namespace
194
195
Raises:
196
ArgumentError: If validation fails
197
"""
198
199
def instantiate_classes(self, cfg: Namespace) -> Namespace:
200
"""
201
Instantiate classes from configuration.
202
203
Args:
204
cfg: Configuration namespace with class specifications
205
206
Returns:
207
Namespace: Configuration with instantiated classes
208
"""
209
210
def strip_unknown(self, cfg: Namespace) -> Namespace:
211
"""
212
Remove unknown keys from configuration.
213
214
Args:
215
cfg: Configuration namespace to process
216
217
Returns:
218
Namespace: Configuration with unknown keys removed
219
"""
220
221
def add_subcommands(self, **kwargs) -> None:
222
"""
223
Add subcommands to the parser.
224
225
Args:
226
**kwargs: Subcommand configuration options including:
227
dest: Destination attribute name for selected subcommand
228
help: Help text for subcommands
229
parser_class: Parser class to use for subcommands
230
"""
231
```
232
233
### ActionsContainer
234
235
Base container class that provides argument management functionality used by ArgumentParser.
236
237
```python { .api }
238
class ActionsContainer:
239
def add_argument(self, *args, **kwargs) -> Action:
240
"""
241
Add an argument to the parser.
242
243
Args:
244
*args: Positional argument names or flags
245
**kwargs: Argument configuration options
246
247
Returns:
248
Action: The created argument action
249
"""
250
251
def add_argument_group(self, title: Optional[str] = None, description: Optional[str] = None) -> ArgumentGroup:
252
"""
253
Create a new argument group.
254
255
Args:
256
title: Group title
257
description: Group description
258
259
Returns:
260
ArgumentGroup: New argument group
261
"""
262
```
263
264
## Usage Examples
265
266
### Basic Parser Setup
267
268
```python
269
from jsonargparse import ArgumentParser
270
271
# Create parser with environment support
272
parser = ArgumentParser(
273
prog="myapp",
274
description="My application",
275
env_prefix="MYAPP_", # Environment variables like MYAPP_NAME
276
default_config_files=["~/.myapp.yaml", "./config.yaml"]
277
)
278
279
# Add arguments
280
parser.add_argument("--name", type=str, required=True)
281
parser.add_argument("--age", type=int, default=30)
282
parser.add_argument("--verbose", action="store_true")
283
```
284
285
### Multi-Source Parsing
286
287
```python
288
# Parse from multiple sources with precedence:
289
# 1. Command line arguments (highest priority)
290
# 2. Configuration files
291
# 3. Environment variables
292
# 4. Default values (lowest priority)
293
config = parser.parse_args()
294
295
# Access parsed values
296
print(f"Name: {config.name}")
297
print(f"Age: {config.age}")
298
print(f"Verbose: {config.verbose}")
299
```
300
301
### Configuration File Handling
302
303
```python
304
# Save current configuration
305
parser.save(config, "current_config.yaml")
306
307
# Load configuration from file
308
file_config = parser.parse_path("config.yaml")
309
310
# Parse configuration string
311
yaml_str = "name: Alice\nage: 25\nverbose: true"
312
string_config = parser.parse_string(yaml_str)
313
```
314
315
### Validation and Processing
316
317
```python
318
# Validate configuration
319
validated_config = parser.validate(config)
320
321
# Merge configurations
322
merged_config = parser.merge_config(default_config, user_config)
323
324
# Generate configuration output
325
yaml_output = parser.dump(config, format="yaml")
326
json_output = parser.dump(config, format="json")
327
```