argparse documentation Help

Arity

Sometimes an argument might accept more than one value. This is especially a case when a data member is an array or associative array. In this case argparse supports two ways of specifying multiple values for an argument:

argparse supports these use cases for arity:

  • Exact number of values.

  • Limited range of minimum-maximum number of values.

  • Unlimited range where only minimum number of values is provided (e.g. argument accepts any number of values).

To adjust the arity, use one the following API:

  • NumberOfValues(size_t min, size_t max) – sets both minimum and maximum number of values.

  • NumberOfValues(size_t num) – sets the exact number of values.

  • MinNumberOfValues(size_t min) – sets minimum number of values.

  • MaxNumberOfValues(size_t max) – sets maximum number of values.

Example:

import argparse; struct T { @(NamedArgument.NumberOfValues(1,3)) int[] a; @(NamedArgument.NumberOfValues(2)) int[] b; } T t; assert(CLI!T.parseArgs(t, ["-a","1","2","3","-b","4","5"])); assert(t == T([1,2,3], [4,5]));

Default arity

Type

Default arity

Notes

bool

0

Boolean flags do not accept values with the only exception when they are specified in --flag=true format in command line.

String or scalar

1

Exactly one value is accepted.

Static array

Length of array

If a range is desired then use provided API to adjust arity.

Dynamic array

1 ... ∞

Associative array

1 ... ∞

function ()

0

Same as boolean flag.

function (string)

1

Same as string.

function (string[])

1 ... ∞

Same as string[] array.

function (RawParam)

1 ... ∞

Same as string[] array.

Named arguments with no values

Sometimes named arguments are can have no values in command line. Here are two cases that arise in this situation:

  • Argument should get specific value if there is no value provided in command line. Use AllowNoValue in this case.

  • Argument must not have any values in command line. Use RequireNoValue in this case.

Both AllowNoValue and RequireNoValue accept a value that should be used when no value is provided in the command line. The difference between them can be seen in this example:

import argparse; struct T { @(NamedArgument.AllowNoValue !10) int a; @(NamedArgument.RequireNoValue!20) int b; } T t; assert(CLI!T.parseArgs(t, ["-a"])); assert(t.a == 10); assert(CLI!T.parseArgs(t, ["-b"])); assert(t.b == 20); assert(CLI!T.parseArgs(t, ["-a","30"])); assert(t.a == 30); assert(!CLI!T.parseArgs(t, ["-b","30"])); // Unrecognized arguments: ["30"]
Last modified: 09 November 2024