Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
atteggiani opened this issue Nov 14, 2024 · 0 comments

Comments

@atteggiani
Copy link
Collaborator

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, ... )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant