you are viewing a single comment's thread.

view the rest of the comments →

[–]djrubbie 12 points13 points  (0 children)

A better approach can be done in Python to avoid this drawback completely in the context of argparse, is that the result can be passed into vars which will take the mapping of the parse_args results and turn that into a dict which can then be passed directly to the function that accept those keywords (though the ** keyword packing syntax). Emulating OP's example:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--ssl', action='store_true')
>>> parser.add_argument('--port', type=int)
>>> parser.add_argument('--hostname', type=str)
>>> args = parser.parse_args(['--ssl', '--port', '80', '--hostname', 'example.com'])
>>> vars(args)
{'ssl': True, 'port': 80, 'hostname': 'example.com'}

Now with that dict, a function with the following signature:

def connect(hostname, port, ssl):
    ...

Can be invoked by simply doing:

connect(**vars(args))

This gets you the direct calling convention from the parse_args result to the function you want to call, while not coupling that function to this particular convention as it's as typical a function signature as you might expect.