Search code examples
pythonargparse

How can I have an aribtrary choice using python argparse?


I'm using argparse, and I'm trying to use choice to limit the options.

For the accepted values, I am looking for the input in the format of: NUMBERkm, NUMBERm, NUMBERcm. For example: 3493cm. I don't care what the number is as long as it ends with a km,cm, or m.

I've tried:

parser.add_argument('-d','--distance',
                    choice=['*m','*km','*cm'])

That didn't work.

As part of my efforts to learn python, I decided to write a small unit conversion script that takes input from arguments.


Solution

  • choices can't be used this way. The test that argparse uses is

    astr in choices
    

    That matches strings in a list, tuple, keys of dictionary. A specialized class could match with a * pattern, but that's more advanced.

    An alternative to choices is to write a custom type function. Or apply that function to the value after parsing.

    Your first task is to come up with a function that tests whether a string meets your criteria

    def mytest(astr):
        if astr ...:
            return astr
        else:
            raise ValueError('your message')
    

    After parsing run

    mytest(args.distance)
    

    Once you get that testing working we can talk about including it in the parser.