or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-actions.mdcli-creation.mdcore-parser.mdindex.mdnamespace-management.mdsettings.mdsignature-arguments.mdtypes-validation.mdutilities.md

index.mddocs/

0

# Jsonargparse

1

2

A comprehensive Python library for creating command-line interfaces (CLIs) derived from type hints. Jsonargparse enables developers to build powerful, configurable Python applications with minimal boilerplate code by automatically generating argument parsers from function and class signatures. It supports parsing from command line arguments, configuration files (YAML, JSON, TOML, Jsonnet), and environment variables simultaneously, making it ideal for machine learning frameworks, data processing pipelines, and any Python application requiring sophisticated configuration management.

3

4

## Package Information

5

6

- **Package Name**: jsonargparse

7

- **Language**: Python

8

- **Installation**: `pip install jsonargparse`

9

- **Documentation**: https://jsonargparse.readthedocs.io/en/stable/

10

11

## Core Imports

12

13

```python

14

import jsonargparse

15

from jsonargparse import ArgumentParser, CLI, auto_cli

16

```

17

18

Common patterns:

19

20

```python

21

# For manual parser creation

22

from jsonargparse import ArgumentParser, Namespace

23

24

# For automatic CLI creation

25

from jsonargparse import auto_cli, CLI

26

27

# For signature-based arguments

28

from jsonargparse import SignatureArguments

29

30

# For advanced features

31

from jsonargparse import ActionConfigFile, ActionYesNo, lazy_instance

32

```

33

34

## Basic Usage

35

36

### Automatic CLI Creation

37

38

```python

39

from jsonargparse import auto_cli

40

41

def main(

42

name: str,

43

age: int = 25,

44

verbose: bool = False

45

) -> None:

46

"""Simple CLI function.

47

48

Args:

49

name: Person's name

50

age: Person's age

51

verbose: Enable verbose output

52

"""

53

if verbose:

54

print(f"Processing for {name}, age {age}")

55

else:

56

print(f"Hello {name}!")

57

58

if __name__ == "__main__":

59

# Automatically creates CLI from function signature

60

auto_cli(main)

61

```

62

63

### Manual Parser Creation

64

65

```python

66

from jsonargparse import ArgumentParser

67

68

# Create parser

69

parser = ArgumentParser(

70

prog="myapp",

71

description="My application",

72

env_prefix="MYAPP_",

73

default_config_files=["~/.myapp.yaml"]

74

)

75

76

# Add arguments

77

parser.add_argument("--name", type=str, required=True, help="Person's name")

78

parser.add_argument("--age", type=int, default=25, help="Person's age")

79

parser.add_argument("--verbose", action="store_true", help="Enable verbose output")

80

81

# Parse arguments

82

config = parser.parse_args()

83

print(f"Hello {config.name}!")

84

```

85

86

### Configuration File Support

87

88

```python

89

from jsonargparse import ArgumentParser

90

91

parser = ArgumentParser()

92

parser.add_argument("--config", action="config_file", help="Path to config file")

93

parser.add_argument("--name", type=str)

94

parser.add_argument("--age", type=int, default=25)

95

96

# Can parse from command line and config file

97

# python script.py --config config.yaml --name Alice

98

config = parser.parse_args()

99

```

100

101

## Architecture

102

103

Jsonargparse builds upon Python's argparse with several key enhancements:

104

105

- **Enhanced ArgumentParser**: Extends argparse.ArgumentParser with configuration file support, environment variable parsing, and advanced type handling

106

- **Namespace Objects**: Nested namespace support with dictionary-like access and serialization capabilities

107

- **Signature Integration**: Automatic argument creation from function, method, and class signatures using type hints

108

- **Action System**: Extensible action classes for complex argument handling patterns

109

- **Type System**: Comprehensive support for Python type hints including generics, unions, and custom classes

110

- **Configuration Sources**: Unified parsing from multiple sources with precedence handling

111

112

## Capabilities

113

114

### Core Parser Functionality

115

116

The ArgumentParser class provides the foundation for all argument parsing with support for multiple configuration sources, advanced type handling, and nested configurations.

117

118

```python { .api }

119

class ArgumentParser:

120

def __init__(self,

121

env_prefix: Union[bool, str] = True,

122

formatter_class: Type = DefaultHelpFormatter,

123

exit_on_error: bool = True,

124

logger: Union[bool, str, dict, logging.Logger] = False,

125

version: Optional[str] = None,

126

print_config: Optional[str] = "--print_config",

127

parser_mode: str = "yaml",

128

default_config_files: Optional[List[Union[str, os.PathLike]]] = None,

129

**kwargs

130

): ...

131

132

def parse_args(self, args: Optional[List[str]] = None) -> Namespace: ...

133

def parse_path(self, cfg_path: Union[str, os.PathLike]) -> Namespace: ...

134

def parse_string(self, cfg_str: str) -> Namespace: ...

135

def dump(self, cfg: Optional[Namespace] = None, **kwargs) -> str: ...

136

def save(self, cfg: Namespace, path: Union[str, os.PathLike], **kwargs) -> None: ...

137

```

138

139

[Core Parser](./core-parser.md)

140

141

### Automatic CLI Creation

142

143

Functions for creating command-line interfaces automatically from function and class signatures with minimal boilerplate code.

144

145

```python { .api }

146

def auto_cli(

147

components: Optional[Union[Callable, List, Dict]] = None,

148

args: Optional[List[str]] = None,

149

as_positional: bool = True,

150

fail_untyped: bool = True,

151

**kwargs

152

) -> Any: ...

153

154

def CLI(*args, **kwargs) -> Any: ... # Alias of auto_cli

155

156

def auto_parser(

157

components: Optional[Union[Callable, List, Dict]] = None,

158

**kwargs

159

) -> ArgumentParser: ...

160

```

161

162

[CLI Creation](./cli-creation.md)

163

164

### Signature-Based Arguments

165

166

Tools for adding arguments based on function, method, and class signatures with automatic type detection and documentation generation.

167

168

```python { .api }

169

class SignatureArguments:

170

def add_class_arguments(self,

171

theclass: Type,

172

nested_key: Optional[str] = None,

173

as_group: bool = True,

174

skip: Optional[Set[str]] = None,

175

**kwargs

176

) -> List[str]: ...

177

178

def add_method_arguments(self,

179

theclass: Type,

180

themethod: str,

181

**kwargs

182

) -> List[str]: ...

183

184

def add_function_arguments(self,

185

function: Callable,

186

**kwargs

187

) -> List[str]: ...

188

189

def compose_dataclasses(*dataclasses: Type) -> Type: ...

190

```

191

192

[Signature Arguments](./signature-arguments.md)

193

194

### Namespace and Configuration Management

195

196

Enhanced namespace objects with nested structure support, serialization capabilities, and configuration manipulation tools.

197

198

```python { .api }

199

class Namespace:

200

def __init__(self, *args, **kwargs): ...

201

def __getitem__(self, key: str) -> Any: ...

202

def __setitem__(self, key: str, value: Any) -> None: ...

203

def as_dict(self) -> Dict[str, Any]: ...

204

def clone(self) -> "Namespace": ...

205

def update(self, value: Union["Namespace", Any]) -> "Namespace": ...

206

def get(self, key: str, default: Any = None) -> Any: ...

207

208

def dict_to_namespace(obj: Dict[str, Any]) -> Namespace: ...

209

def strip_meta(cfg: Union[Namespace, Dict]) -> Union[Namespace, Dict]: ...

210

```

211

212

[Namespace Management](./namespace-management.md)

213

214

### Advanced Actions

215

216

Specialized action classes for handling complex argument patterns including configuration files, yes/no options, and custom validation.

217

218

```python { .api }

219

class ActionConfigFile:

220

def __init__(self, **kwargs): ...

221

222

class ActionYesNo:

223

def __init__(self, yes_prefix: str = "", no_prefix: str = "no_", **kwargs): ...

224

225

class ActionFail:

226

def __init__(self, message: str = "option unavailable", **kwargs): ...

227

228

class ActionJsonSchema:

229

def __init__(self, schema: Union[str, Dict], **kwargs): ...

230

231

class ActionJsonnet:

232

def __init__(self, **kwargs): ...

233

```

234

235

[Advanced Actions](./advanced-actions.md)

236

237

### Utilities and Type Support

238

239

Utility functions and classes for path handling, lazy instantiation, and advanced type support.

240

241

```python { .api }

242

class Path:

243

def __init__(self, path: Union[str, os.PathLike], mode: str = "fr"): ...

244

def __str__(self) -> str: ...

245

@property

246

def absolute(self) -> pathlib.Path: ...

247

248

def lazy_instance(init_fn: Callable[[], Any]) -> Any: ...

249

def capture_parser() -> ArgumentParser: ...

250

def class_from_function(function: Callable, *args, **kwargs) -> Type: ...

251

```

252

253

[Utilities](./utilities.md)

254

255

### Configuration and Settings

256

257

Functions for customizing parsing behavior, loader/dumper settings, and global configuration options.

258

259

```python { .api }

260

def set_parsing_settings(

261

validation: Optional[bool] = None,

262

docstring_parser: Optional[str] = None,

263

parse_as_dict: Optional[bool] = None,

264

**kwargs

265

) -> None: ...

266

267

def set_loader(mode: str, loader: Callable[[str], Any]) -> None: ...

268

def set_dumper(mode: str, dumper: Callable[[Any], str]) -> None: ...

269

def get_loader(mode: str) -> Callable[[str], Any]: ...

270

def get_dumper(mode: str) -> Callable[[Any], str]: ...

271

```

272

273

[Settings](./settings.md)

274

275

### Types and Validation

276

277

Advanced type system with built-in validators, custom type registration, and predefined types for common validation patterns.

278

279

```python { .api }

280

def register_type(custom_type: Type, serializer: Optional[Callable] = None) -> None: ...

281

def restricted_number_type(base_type: Union[Type[int], Type[float]], **kwargs) -> Type: ...

282

def restricted_string_type(pattern: Optional[str] = None, **kwargs) -> Type: ...

283

def path_type(mode: str) -> Type: ...

284

285

# Predefined numeric types

286

PositiveInt: Type

287

PositiveFloat: Type

288

NonNegativeInt: Type

289

NonNegativeFloat: Type

290

ClosedUnitInterval: Type

291

OpenUnitInterval: Type

292

293

# Predefined string types

294

NotEmptyStr: Type

295

Email: Type

296

SecretStr: Type

297

298

# Predefined path types

299

Path_fr: Type

300

Path_fc: Type

301

Path_dw: Type

302

Path_dc: Type

303

Path_drw: Type

304

```

305

306

[Types and Validation](./types-validation.md)

307

308

## Types

309

310

```python { .api }

311

# Import types from argparse

312

from argparse import ArgumentError, OPTIONAL, REMAINDER, SUPPRESS, PARSER, ONE_OR_MORE, ZERO_OR_MORE

313

314

# Core namespace type

315

from typing import Union, Optional, List, Dict, Any, Callable, Type

316

```