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

Dispatch a Python method call with variable number of arguments by using an array slice

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:

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

"""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?

>Solution :

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
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