argparse argument may be str or int and the simplest way to handle it

I didn’t know quite how to word the title but I’m trying to enter two variables with argparse. The first argument may be a string or an integer and the second argument will always be an integer.

The first example would be python calnum.py -x 2 -y 4. In my sample code below it sees the first argument as a string and not an int. I didn’t specify type=int because of the second valid example below.

The other example would be python calnum.py -x curve -y 0.

If the first argument is curve then the 2nd argument should be 0. Below I set it to zero which works or is it better practice to display an error and have the user actually enter 0 for the second argument if they didn’t enter zero or use the help command?

Actually if it’s set to curve then y doesn’t need to be entered at all and just set y = 0 but if a user enters something should I do something with it or ignore it and set it to 0 like in the code below or go about it another way entirely.

Also what is the best way to handle the first argument in regards to being an int. First verify if it’s an int and then convert it to an int to do calculations? I have some code below and don’t quite know what to do with it. I might be going about it all wrong possibly as I just started reading about argparse.

Is there any easy (short) way to handle those two examples from the command line? I prefer the easy to read code vs. short and complex as my experience is limited. Hopefully I explained that well enough and any help would be greatly appreciated or just ask if I missed explaining something, thank you.

import argparse

my_parser = argparse.ArgumentParser()

my_parser.add_argument('-x', action='store')
my_parser.add_argument('-y', action='store', type=int)

args = my_parser.parse_args()

if args.x == "curve":
    args.y = 0
elif str.isdigit(args.x):
    args.x = int(args.x)

Answer

Best way to handle it is to read it as a string, and use the function str.isdecimal to check if it’s a number. If it is, you’re safe to cast to int using int(val), otherwise, treat it as a string.

Maybe like this:

import argparse

my_parser = argparse.ArgumentParser()

my_parser.add_argument('-x', action='store')
my_parser.add_argument('-y', action='store', type=int)

args = my_parser.parse_args()

if args.x.isdecimal():
    as_int = int(args.x)
else:
    args.y = 0