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:
python ./my_script.py --resize # Will contain True that means, resize all the objects
python ./my_script.py --resize <index> # Will contain index, that means resize only specific object
You can add
default=False
,const=True
andnargs='?'
to the argument definition and removeaction
. This way if you don't pass--resize
it will store False, if you pass--resize
with no argument will storeTrue
and otherwise the passed argument. Still you will have to refactor the code a bit to know if you have index to delete or delete all objects.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’sconst
value, so that’s what you need to specify too:There are now three cases for this argument:
Not specified: The argument will get its default value (
None
by default):Specified without a value: The argument will get its const value:
Specified with a value: The argument will get the specified value:
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 getNone
orTrue
in those cases:Your usage would then look something like this:
Use
nargs
to accept different number of command-line argumentsUse
default
andconst
to set the default value of resizesee here for details: https://docs.python.org/3/library/argparse.html#nargs