Friday, November 15, 2019

[Python] Removing hard-coded number with argparse

Assume you have a function as below in a python script calculate_sum.py,

def summing(a, b):
    return a+b
summing(2,3)

Now if you want to change 2 and 3 to other numbers, you can use a powerful tool argparse instead of modifying these hard-coded numbers in the script, which can be complicated in a set of complicated scripts. 

import argparse

parser = argparse.ArgumentParser(description='calculate the sum of two numbers')

# Either use positional arguments. The position matters, so a and b can not reverse in order.
parser.add_argument('a', type=int)
parser.add_argument('b', type=int)

# Or use optional arguments. The position of a and b does not matter.
parser.add_argument('--a', type=int)
parser.add_argument('--b', type=int)

# Pass the arguments to the parser python module
args = parser.parse_args()

def summing(a, b):
    return a+b
summing(args.a,args.b)

If you use positional arguments, your command should be:
$python calculate_sum.py 4 3
7

Otherwise, your command should be:
$python calculate_sum.py --a 4 --b 3
7


No comments:

Post a Comment