Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create argument in python's argparse that returns true in case no values given

Currently --resize flag that I created is boolean, and means that all my objects will be resized:

parser.add_argument("--resize", action="store_true", help="Do dictionary resize")

# ...

# if resize flag is true I'm re-sizing all objects
if args.resize:
    for object in my_obects:
        object.do_resize()

Is there a way implement argparse argument that if passed as boolean flag (--resize) will return true, but if passed with value (--resize 10), will contain value.

Example:

  1. python ./my_script.py --resize # Will contain True that means, resize all the objects
  2. python ./my_script.py --resize <index> # Will contain index, that means resize only specific object
like image 960
Samuel Avatar asked Dec 27 '25 16:12

Samuel


1 Answers

In order to optionally accept a value, you need to set nargs to '?'. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s const value, so that’s what you need to specify too:

parser = argparse.ArgumentParser()
parser.add_argument('--resize', nargs='?', const=True)

There are now three cases for this argument:

  1. Not specified: The argument will get its default value (None by default):

    >>> parser.parse_args(''.split())
    Namespace(resize=None)
    
  2. Specified without a value: The argument will get its const value:

    >>> parser.parse_args('--resize'.split())
    Namespace(resize=True)
    
  3. Specified with a value: The argument will get the specified value:

    >>> parser.parse_args('--resize 123'.split())
    Namespace(resize='123')
    

Since you are looking for an index, you can also specify type=int so that the argument value will be automatically parsed as an integer. This will not affect the default or const case, so you still get None or True in those cases:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--resize', nargs='?', type=int, const=True)
>>> parser.parse_args('--resize 123'.split())
Namespace(resize=123)

Your usage would then look something like this:

if args.resize is True:
    for object in my_objects:
        object.do_resize()
elif args.resize:
    my_objects[args.resize].do_resize()
like image 127
poke Avatar answered Dec 30 '25 05:12

poke