Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading