ACCESS-NRI / umfile_utils

0 stars 0 forks source link

Add restrictions to command-line arguments directly in the function that parses arguments #10

Open atteggiani opened 1 week ago

atteggiani commented 1 week ago

Description

If any command line arguments need further restrictions than a simple "type" restriction (for example if they need to be a non-negative integer), it would be good to add these restrictions directly in the function that passes arguments.

Why is this useful

This would be useful so the program will "fail fast" right within the parsing function if the user passes any option values that don't meet the requirements, without waiting for another function to perform the sanity check later in the program.

How can it be implemented

The argparse.add_argument type argument can be set to any callable. This could be set to a function that checks the specific restriction. For example, to restrict a value to be a non-negative integer, the following function can be implemented:

def check_non_negative(value: str) -> int:
    msg = "Value must be a non-negative integer."
    try:
        ivalue = int(value)
    except ValueError:
        raise argparse.ArgumentTypeError(msg)
    if ivalue < 0:
        raise argparse.ArgumentTypeError(msg)
    return ivalue

And then, the argparse.ArgumentParser.add_argument line could be something like:

parser.add_argument(
        "--non-negative-option", type=check_non_negative, ... )