Search code examples
pythonpython-3.xargparse

How to store an 'args.foo' value to a 'bar' variable?


I have been using the argparse for my latest project and although it is extremely helpful, I have realized that most of the time, especially in longer scripts, I try to avoid using the variable with the 'args.' prefix, so lines like this are bloating my code:

parser.add_argument('--learning_rate', '--lr', default=0.0005, type=float, help='defines the learning_rate variable for the model.')
learning_rate = args.learning_rate

is there an option to automatically store the content passed to --learning_rate into learning_rate, avoiding this second line of code?

Thanks for your time and attention.


Solution

  • As others have said, removing the line referencing args.learning_rate will lead to others finding your code cryptic or confusing.

    But something like this could be used in code golfing, so I will offer a 'cryptic' way of doing this under the assumption that you have several arguments that you do not want to have to reassign line-by-line.

    You could acquire the dictionary of args using the vars() built-in function or __dict__ attribute.
    Please reference What is the right way to treat Python argparse.Namespace() as a dictionary.

    >>> import argparse
    >>> args = argparse.Namespace()
    >>> args.foo = 1
    >>> args.bar = [1,2,3]
    >>> d = vars(args)
    >>> d
    {'foo': 1, 'bar': [1, 2, 3]}
    

    Afterwards you could convert these keys to variables and assign the values to the variable like so:

    for k, v in d.items():
        exec(f'{k} = {v}')
    print(foo) # 1
    print(bar) # [1, 2, 3]
    

    Please see Using a string variable as a variable name for additional insight to why exec() may be bad practice and setattr may be more appropriate if you resort to this method.