Search code examples
pythonargparse

Python argparse with two defaults when the argument is and is not specified


For the argument -f, I want it

  1. to have a default value when it's not specified in the command.
  2. to have another default value when it is specified in the command but no values were given
  3. to allow user to give single or multiple values to this argument

Solution

  • If you want only one value to be consumed for your option then the code in the comment on your question is enough.

    If you want more than one argument for your option then const cannot be used in add_argument ('?' is needed for nargs), instead you can subclass Action class (found in argparse):

    class FAction(argparse.Action):
        #The default to use in case the option is provided by
        #the user, you can make it local to __call__
        __default2 = 'def2'
        #__call__ is called if the user provided the option
        def __call__(self, parser, namespace, values, option_string=None):
            #If the option f is provided with no arguments
            #then use __default2 which is the second default
            #if values length is 0< then use what the user
            #has provided
            if len(values) == 0:
                values = self.__default2
            setattr(namespace, self.dest, values)
    
    parser = argparse.ArgumentParser(description='Program arguments')
    parser.add_argument('-f', default='def', nargs='*', action=FAction)
    
    args = parser.parse_args()
    
    print(args.f)