0

In an application I need to have an optional parameter. And if that parameter is given the value has a default/optional setting.

IE the following cases:

python main.py  # value stored should be "None" (Or other indication optional parameter is not given
python main.py --ls  # value stored should be the default value ("testdir")
python main.py --ls=otherdir  # value stored should be 'otherdir'

However if the parser is setup like:

parser = argparse.ArgumentParser(description='Modify docker container definitions')
parser.add_argument('--ls', default='testdir', help="list")

it works quite differently:

python main.py  # value is 'testdir'
python main.py --ls  # error (missing argument)
python main.py --ls=otherdir  # value is 'otherdir'

How can I make argparse work like this? Or is there a logical reason such a setup cannot work?

paul23
  • 8,799
  • 12
  • 66
  • 149
  • As defined `--ls` expects one argument. But if you make it 'optional', `nargs='?'` it will have the 3 way behavior you want. That use of '?' is inspired by `regex` notation. – hpaulj Jul 19 '23 at 15:06

0 Answers0