Skip to content

Accepting empty values #251

@junapur

Description

@junapur

According to the Docs:

num_args=-1 can be used to indicate that 0 or more (i.e. unbounded number of) arguments will be consumed, similarly resulting in a sequence-type output (even in the zero case).

Though if I do the following:

    numbers: Annotated[
        list[int],
        cappa.Arg(
            long=True,
            default=[1, 2, 3],
            num_args=-1,
        ),
    ]

# $ uv run my_cli --numbers
# Error: Argument '--numbers' requires at least one values, found 0

I would expect to just get an empty list, as the docs say "resulting in a sequence-type output (even in the zero case)."

argparse does have the behavior I want:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument(
    '--numbers',
    nargs='*',
    type=list[int],
    default=[1, 2, 3],
    help='List of numbers (default: [1, 2, 3], pass flag alone for [])'
)

args = parser.parse_args()
print(f"{args.numbers=}")

# $ uv run my_cli --numbers
# args.numbers=[]

In the same vein, is there a way to specify something similar to argparse's nargs='?' parameter in cappa?

import argparse

parser = argparse.ArgumentParser()

parser.add_argument(
    '--number',
    type=int,
    nargs='?',
    default=5,
    help='A number (default: 5, pass flag alone for None value)'
)

args = parser.parse_args()
print(f"{args.number=}")

# $ uv run my_cli --number
# args.number=None

Though I understand passing an arg without any values in order to produce a NoneType or empty sequence could be confusing to some CLI users. Also, thank you for all your hard work on this project, it's amazing and much appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions