0

I have a small Python tracking script with a couple of possible modes (e.g. "add" and "show") that correspond to methods that take different numbers of arguments.

I want to check the mode argument is valid, and if so, then call the appropriate method with all remaining command line arguments passed as individual parameters.

The code I have looks like this:

"""python tracking.py add <person> <date> <score> 
   python tracking.py show <person> <date>
"""
if __name__ == "__main__":
    tracking = TrackingData()
    modes = {'add': tracking.add_data, 'show': tracking.print_data }

    mode = sys.argv[1]

    # If mode is valid
    modes[mode](sys.argv[2:])

    # Original code looks a bit like this: 
    #
    # person = sys.argv[2]
    # date = sys.argv[3]
    # score = sys.argv[4]

    # tracking.add_data(person, date, score)
    # tracking.print_data(person, date)

However, the code gives a TypeError: print_data() missing 1 required positional argument: 'date' - so presumably the array slice is being passed as a single parameter, whereas I need it to be flattened into its component entries.

What's the best way to do this? Are there any better patterns for this type of dispatch table / modal action approach?

2
  • To pass on keyword arguments using dictionaries you can use the **. This requires a dictionary creation Commented Jan 30, 2022 at 18:35
  • Alternatively, I think it may be possible to use a wrapper that takes the list and places the variables properly into the original function call. I am not aware of any method that automatically places list positions as positional arguments. Commented Jan 30, 2022 at 18:41

1 Answer 1

0

Using * will unpack values from a list into positional arguments. So you would just need to change your dispatch line to look like this:

modes[mode](*sys.argv[2:])

For example:

def add3(a, b, c):
    return a + b + c

nums = [1, 2, 3]

add3(*nums) # 6
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.