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

Solution 1:

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.

Solution 2:

When you call a function, an argument is implicitly assigned to a parameter.

In the same scope where args is defined, I would continue using args.learning_rate to emphasize that it is a configuration option. But instead of writing

def foo(x):
    return x * args.learning_rate

y = foo(3)

write

def foo(x, learning_rate):
    return x * learning_rate

y = foo(args.learning_rate)

When reading the definition of foo, you don't care how learning_rate will be set at call time.