Search code examples
pythonargparse

Disable argparse arguments from being overwritten


I have a legacy Python application which uses some options in its CLI, using argparse, like:

parser = argparse.ArgumentParser()
parser.add_argument('-f', default='foo')

Now I need to remove this option, since now its value cannot be overwritten by users but it has to assume its default value (say 'foo' in the example). Is there a way to keep the option but prevent it to show up and be overwritten by users (so that I can keep the rest of the code as it is)?


Solution

  • It's not entirely clear what you can do, not with the parser. Can you edit the setup? Or just modify results of parsing?

    If you can edit the setup, you could replace the add_argument line with a

    parser.setdefaults(f='foo')
    

    https://docs.python.org/3/library/argparse.html#parser-defaults

    The -f won't appear in the usage or help, but it will appear in the args

    Or you could leave it in, but suppress the help display

    parser.add_argument('-f', default='foo', help=argparse.SUPPRESS)
    

    https://docs.python.org/3/library/argparse.html#help

    Setting the value after parsing is also fine.