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

advanced-actions.mddocs/

0

# Advanced Actions

1

2

Specialized action classes for handling complex argument patterns including configuration files, yes/no options, JSON schema validation, Jsonnet processing, and custom validation. These actions extend the standard argparse action system with advanced functionality for sophisticated CLI applications.

3

4

## Capabilities

5

6

### Configuration File Action

7

8

Action for handling configuration file arguments that can parse and merge configuration from files or strings.

9

10

```python { .api }

11

class ActionConfigFile:

12

def __init__(self, **kwargs):

13

"""

14

Initialize configuration file action.

15

16

Args:

17

**kwargs: Standard argparse action keyword arguments

18

"""

19

20

def __call__(self, parser, cfg, values, option_string=None) -> None:

21

"""

22

Process configuration file argument.

23

24

Args:

25

parser: ArgumentParser instance

26

cfg: Current configuration namespace

27

values: Configuration file path or string

28

option_string: Option string that triggered this action

29

"""

30

31

@staticmethod

32

def apply_config(parser, cfg, dest, value) -> None:

33

"""

34

Apply configuration to parser.

35

36

Args:

37

parser: ArgumentParser instance

38

cfg: Configuration namespace to update

39

dest: Destination attribute name

40

value: Configuration value to apply

41

"""

42

```

43

44

### Yes/No Action

45

46

Action that creates paired boolean options with customizable prefixes for setting True/False values.

47

48

```python { .api }

49

class ActionYesNo:

50

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

51

"""

52

Initialize yes/no action with customizable prefixes.

53

54

Args:

55

yes_prefix: Prefix for the "yes" option (empty for base name)

56

no_prefix: Prefix for the "no" option (default: "no_")

57

**kwargs: Standard argparse action keyword arguments

58

"""

59

60

def __call__(self, parser, namespace, values, option_string=None) -> None:

61

"""

62

Process yes/no argument.

63

64

Args:

65

parser: ArgumentParser instance

66

namespace: Namespace to update

67

values: Argument values (unused for boolean flags)

68

option_string: Option string that triggered this action

69

"""

70

```

71

72

### Fail Action

73

74

Action that always fails with a custom error message, useful for deprecating or disabling options.

75

76

```python { .api }

77

class ActionFail:

78

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

79

"""

80

Initialize fail action with custom error message.

81

82

Args:

83

message: Error message to display when action is triggered

84

**kwargs: Standard argparse action keyword arguments

85

"""

86

87

def __call__(self, parser, namespace, values, option_string=None) -> None:

88

"""

89

Always raise an ArgumentError with the configured message.

90

91

Args:

92

parser: ArgumentParser instance

93

namespace: Namespace (unused)

94

values: Argument values (unused)

95

option_string: Option string that triggered this action

96

97

Raises:

98

ArgumentError: Always raised with the configured message

99

"""

100

```

101

102

### JSON Schema Action

103

104

Action for parsing and validating JSON arguments against a JSON schema.

105

106

```python { .api }

107

class ActionJsonSchema:

108

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

109

"""

110

Initialize JSON schema action.

111

112

Args:

113

schema: JSON schema as string (path) or dict (schema object)

114

**kwargs: Standard argparse action keyword arguments

115

"""

116

117

def __call__(self, parser, namespace, values, option_string=None) -> None:

118

"""

119

Parse and validate JSON against schema.

120

121

Args:

122

parser: ArgumentParser instance

123

namespace: Namespace to update

124

values: JSON string or file path to validate

125

option_string: Option string that triggered this action

126

127

Raises:

128

ArgumentError: If JSON is invalid or doesn't match schema

129

"""

130

```

131

132

### Jsonnet Action

133

134

Action for parsing Jsonnet configuration files with optional JSON schema validation.

135

136

```python { .api }

137

class ActionJsonnet:

138

def __init__(self, **kwargs):

139

"""

140

Initialize Jsonnet action.

141

142

Args:

143

**kwargs: Standard argparse action keyword arguments plus:

144

schema: Optional JSON schema for validation

145

ext_vars: External variables for Jsonnet

146

"""

147

148

def __call__(self, parser, namespace, values, option_string=None) -> None:

149

"""

150

Parse Jsonnet file or string.

151

152

Args:

153

parser: ArgumentParser instance

154

namespace: Namespace to update

155

values: Jsonnet file path or string

156

option_string: Option string that triggered this action

157

158

Raises:

159

ArgumentError: If Jsonnet parsing fails or validation fails

160

"""

161

```

162

163

### Parser Action

164

165

Action for parsing options with a nested ArgumentParser, optionally loading from files.

166

167

```python { .api }

168

class ActionParser:

169

def __init__(self, parser: Optional[ArgumentParser] = None, **kwargs):

170

"""

171

Initialize parser action with nested parser.

172

173

Args:

174

parser: ArgumentParser to use for parsing (created if None)

175

**kwargs: Standard argparse action keyword arguments

176

"""

177

178

def __call__(self, parser, namespace, values, option_string=None) -> None:

179

"""

180

Parse values using nested parser.

181

182

Args:

183

parser: Parent ArgumentParser instance

184

namespace: Namespace to update

185

values: String or file path to parse

186

option_string: Option string that triggered this action

187

"""

188

```

189

190

## Usage Examples

191

192

### Configuration File Handling

193

194

```python

195

from jsonargparse import ArgumentParser, ActionConfigFile

196

197

parser = ArgumentParser()

198

199

# Add configuration file argument

200

parser.add_argument(

201

"--config",

202

action=ActionConfigFile,

203

help="Path to configuration file or configuration string"

204

)

205

206

# Add other arguments

207

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

208

parser.add_argument("--value", type=int, default=42)

209

210

# Parse arguments - config file values are merged

211

config = parser.parse_args()

212

213

print(f"Name: {config.name}")

214

print(f"Value: {config.value}")

215

```

216

217

With config file `settings.yaml`:

218

```yaml

219

name: "from_config"

220

value: 100

221

```

222

223

Usage:

224

```bash

225

# Load from file

226

python script.py --config settings.yaml --name "override"

227

228

# Load from string

229

python script.py --config '{"name": "json_config", "value": 200}'

230

```

231

232

### Yes/No Options

233

234

```python

235

from jsonargparse import ArgumentParser, ActionYesNo

236

237

parser = ArgumentParser()

238

239

# Standard yes/no option (--verbose / --no_verbose)

240

parser.add_argument(

241

"--verbose",

242

action=ActionYesNo,

243

help="Enable verbose output"

244

)

245

246

# Custom prefixes (--enable-debug / --disable-debug)

247

parser.add_argument(

248

"--debug",

249

action=ActionYesNo,

250

yes_prefix="enable-",

251

no_prefix="disable-",

252

help="Enable debug mode"

253

)

254

255

config = parser.parse_args()

256

257

print(f"Verbose: {config.verbose}")

258

print(f"Debug: {config.debug}")

259

```

260

261

Usage:

262

```bash

263

python script.py --verbose --enable-debug # Both True

264

python script.py --no_verbose --disable-debug # Both False

265

python script.py --verbose --disable-debug # verbose=True, debug=False

266

```

267

268

### Deprecated Options

269

270

```python

271

from jsonargparse import ArgumentParser, ActionFail

272

273

parser = ArgumentParser()

274

275

# Current option

276

parser.add_argument("--output-format", type=str, default="json")

277

278

# Deprecated option that fails with helpful message

279

parser.add_argument(

280

"--format",

281

action=ActionFail,

282

message="Option --format is deprecated. Use --output-format instead."

283

)

284

285

config = parser.parse_args()

286

```

287

288

Usage:

289

```bash

290

python script.py --output-format yaml # Works

291

python script.py --format json # Fails with helpful message

292

```

293

294

### JSON Schema Validation

295

296

```python

297

from jsonargparse import ArgumentParser, ActionJsonSchema

298

299

# Define JSON schema

300

user_schema = {

301

"type": "object",

302

"properties": {

303

"name": {"type": "string"},

304

"age": {"type": "integer", "minimum": 0},

305

"email": {"type": "string", "format": "email"}

306

},

307

"required": ["name", "age"]

308

}

309

310

parser = ArgumentParser()

311

312

# Add JSON argument with schema validation

313

parser.add_argument(

314

"--user",

315

action=ActionJsonSchema,

316

schema=user_schema,

317

help="User information as JSON"

318

)

319

320

config = parser.parse_args()

321

322

if config.user:

323

print(f"User: {config.user['name']}, Age: {config.user['age']}")

324

```

325

326

Usage:

327

```bash

328

# Valid JSON

329

python script.py --user '{"name": "Alice", "age": 30, "email": "alice@example.com"}'

330

331

# Invalid JSON (missing required field)

332

python script.py --user '{"name": "Bob"}' # Fails validation

333

334

# From file

335

echo '{"name": "Charlie", "age": 25}' > user.json

336

python script.py --user user.json

337

```

338

339

### Jsonnet Configuration

340

341

```python

342

from jsonargparse import ArgumentParser, ActionJsonnet

343

344

parser = ArgumentParser()

345

346

# Add Jsonnet configuration argument

347

parser.add_argument(

348

"--config",

349

action=ActionJsonnet,

350

help="Jsonnet configuration file or string"

351

)

352

353

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

354

parser.add_argument("--count", type=int)

355

356

config = parser.parse_args()

357

358

print(f"Name: {config.name}")

359

print(f"Count: {config.count}")

360

```

361

362

With Jsonnet file `config.jsonnet`:

363

```jsonnet

364

{

365

name: "jsonnet_config",

366

count: 10 * 5, // Jsonnet expressions

367

computed: "Name is " + self.name

368

}

369

```

370

371

Usage:

372

```bash

373

python script.py --config config.jsonnet

374

```

375

376

### Nested Parser Action

377

378

```python

379

from jsonargparse import ArgumentParser, ActionParser

380

381

# Create nested parser for database configuration

382

db_parser = ArgumentParser()

383

db_parser.add_argument("--host", type=str, default="localhost")

384

db_parser.add_argument("--port", type=int, default=5432)

385

db_parser.add_argument("--username", type=str, required=True)

386

db_parser.add_argument("--password", type=str, required=True)

387

388

# Main parser

389

parser = ArgumentParser()

390

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

391

392

# Add database config as nested parser

393

parser.add_argument(

394

"--database",

395

action=ActionParser,

396

parser=db_parser,

397

help="Database configuration"

398

)

399

400

config = parser.parse_args()

401

402

print(f"App: {config.app_name}")

403

print(f"DB: {config.database.host}:{config.database.port}")

404

```

405

406

Usage:

407

```bash

408

# Inline database config

409

python script.py --app-name MyApp --database "--host db.example.com --port 3306 --username user --password pass"

410

411

# Database config from file

412

echo "--host prod-db --username admin --password secret" > db.conf

413

python script.py --app-name MyApp --database db.conf

414

```

415

416

### Combining Multiple Actions

417

418

```python

419

from jsonargparse import ArgumentParser, ActionConfigFile, ActionYesNo, ActionFail

420

421

parser = ArgumentParser()

422

423

# Configuration file support

424

parser.add_argument("--config", action=ActionConfigFile)

425

426

# Yes/no options

427

parser.add_argument("--verbose", action=ActionYesNo)

428

parser.add_argument("--debug", action=ActionYesNo)

429

430

# Regular arguments

431

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

432

parser.add_argument("--count", type=int, default=1)

433

434

# Deprecated option

435

parser.add_argument(

436

"--old-count",

437

action=ActionFail,

438

message="Use --count instead of --old-count"

439

)

440

441

config = parser.parse_args()

442

443

if config.verbose:

444

print(f"Processing {config.name} with count {config.count}")

445

if config.debug:

446

print("Debug mode enabled")

447

```

448

449

With config file:

450

```yaml

451

name: "config_name"

452

count: 5

453

verbose: true

454

```

455

456

Usage:

457

```bash

458

python script.py --config config.yaml --no_verbose --debug

459

```