Here's an example how you might use a base class with your functions as classes inheriting from it to automatically build your commandline (using the __subclasses__()
method on the base class) and do the calculation, without writing some ridiculous sequence of if statements.
For more info on subclasses see here in the Python documentation.
import argparse
# base class for all your functions to inherit from
class mystuff():
pass
# function classes inherit from mystuff, provide at least a docstring and a calculate() method.
class fun1(mystuff):
'''
Calculate fun1
'''
def calculate(self,value):
return value*2
class fun2(mystuff):
'''
Calculate fun2
'''
def calculate(self,value):
return value*23
if __name__=="__main__":
parser = argparse.ArgumentParser(description="Allow calling functions each defined in their own class")
# find all the classes to be used as commandline arguments
for fun in mystuff.__subclasses__():
# print( f"Creating argument for {fun.__name__}" )
parser.add_argument( f'--{fun.__name__}', default=0, dest='function', action='store_const', const=fun, help=fun.__doc__)
parser.add_argument('variable', type=int, help="Value to pass to calculation")
args = parser.parse_args()
# create an instance and call its calculate function passing the variable value
result = args.function().calculate(args.variable)
print( f"Calling {args.function.__name__} with variable {args.variable} gives result {result}" )
Getting the usage:
fun1.py -h
gives:
usage: fun1.py [-h] [--fun1] [--fun2] variable
Allow calling functions each defined in their own class
positional arguments:
variable Value to pass to calculation
optional arguments:
-h, --help show this help message and exit
--fun1 Calculate fun1
--fun2 Calculate fun2
invoking one of the functions:
fun1.py --fun1 235
gives result:
Calling fun1 with variable 235 gives result 470
I'm sure this could be made more sophisticated, perhaps removing the need for a -- before each function name by using subparsers.