2

I have a set of boolean argparse options: --foo/--no-foo, --bar/--no-bar, --baz/--no-baz

My script makes sense only if at least one of those options is set to True.

I'd like to issue an Exception correctly processed by argparse, which will be managed as a command line error clear message.

But argparse.ArgumentTypeError is not a good option because it required the option as first argument to the constructor ... and my case is related to multiple options.

[Edit based on @00 comment:] The only solution I've got now is to raise, at the end of the command line processing, a ValueError is none of those options are set. But it is an exception, which is not user friendly.

What is the way to proceed in such cases?

Thanks a lot.

P.S.: Code to generate those options:

    @classmethod
    def addBoolean(
        cls, argumentParser, dest, helpTrue, helpFalse,
        default=None
    ):
        """Adds a boolean option
        - argumentParser: A argparse.ArgumentHelper object
        - dest: The destination argument
        - helpTrue: The documentation of the True option
        - helpFalse: The documentation of the False option
        - default: Value to use if not required and not provided

        When no default (None) is provided, required is True

        The option will be --{dest} and --no-{dest}
        """
        # pylint: disable=too-many-arguments

        required = (default is None)
        group = argumentParser.add_mutually_exclusive_group(
            required=required,
        )
        group.add_argument(
            f'--{dest}',
            dest=dest,
            action='store_true',
            help=helpTrue
        )
        group.add_argument(
            f'--no-{dest}',
            dest=dest,
            action='store_false',
            help=helpFalse
        )
        if not required:
            argumentParser.set_defaults(**{dest: default})
Michael Hooreman
  • 582
  • 1
  • 5
  • 16

1 Answers1

0

According to Python argparse: Make at least one argument required:

Flexible argparse errors can be created using parser.error("error message")

(see comments of @fabianegli in the question)

Michael Hooreman
  • 582
  • 1
  • 5
  • 16