Search code examples
pythonargparse

Replace arguments in ArgumentParser


I create a argparse.ArgumentParser instance from a config file, adding arguments from the name and value of entries.

Later in my code I want to specifically set some arguments, lets say --hidden_size is one of them.

When I run

parser.add_argument('--hidden_size', type=int, metavar='N', help='Hidden size')

I get argparse.ArgumentError: argument --hidden_size: conflicting option string: --hidden_size.

What would be the easiest way to replace an entry? Ideally, it should look something like this:

arg = parser['--hidden_size']
parser.add_argument('--hidden_size', type=int, metavar='N', default=arg.default, help='Hidden size')

However, neither can I access the argument by subscripting the parser, nor can I replace an argument with the method add_argument and the same name. How would this be done?


Solution

  • Here is a hack because it relies on hidden attribute of an ArgumentParser:

    import argparse
    
    def lookup(par, arg):
        for action in par._actions:
            if arg in action.option_strings:
                return action
        raise ValueError(f"{arg} not found")
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--hidden_size")
    
    
    try:
        # Lookup --hidden_size and update
        action = lookup(parser, "--hidden_size")
        action.type = int
        action.metavar = "N"
        action.help = "Hidden size"
    except ValueError:
        # Lookup failed, add new
        parser.add_argument('--hidden_size', type=int, metavar='N', help='Hidden size')