Search code examples
pythondjangooopargs

How to have one mandatory and two optional positional arguments?


I need to run a python file as follows

python runnning_program.py argument1 [argument2] [argument3]

def main(argument1,argument2 = default2, argument3 = default2):
   code


if __name__ == '__main__': 
   ap = argparse.ArgumentParser()
   ap.add_argument("argument1")
   kwargs = vars(ap.parse_args())
   main(**kwargs)

How to add argument2 and argument3 as optional positional arguments?


Solution

  • Unfortunately, this does not work.

    To elaborate a little: Positional arguments are mandatory. The quick take-away is, that a function in Python can always (and will always) be treated as having the following signature:

    def some_function(*args, **kwargs):

    This implies that positional arguments are basically just a list of arguments to the interpreter and will be expanded when passed to the function. Therefore, all positional arguments need to be present when calling the function.

    That is a huge difference to how named arguments are passed ("keyword arguments"): They are a dictionary of the kind

    {'parameter_name': 'parameter_value'}

    They are always present as they get defined by having a default value.

    To get back to your original issue: When calling your function, the option to pass kwargs by position instead of by name may help you.

    so, instead of

    main(argument1, argument2 = 'default2', argument3 = 'default3')

    you can always call

    main(argument1, 'default2', 'default3') instead.

    Also, you may want to have a look at the argparse library.