Unpacking arguments from argparse

Viewed 8734

I've been writing some command line python programs and using argparse to do it. I've been structuring my code somewhat as follows.

def main(arg1, arg2):
    # magic
    pass

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('arg1')
    parser.add_argument('arg2')

    args = parser.parse_args()

    main(args.arg1, args.arg2)

It's really super irritating to have to call out arg1 and arg2 3 times. I understand having to do it twice.

Is there some way to treat the namespace returned by the parse_args function as a tuple? Or better yet as a tuple and a dict for optional args and do unpacking?

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('arg1')
    parser.add_argument('arg2')
    parser.add_argument('--opt-arg', default='default_value')

    args, kwargs = parser.magic_method_call_that_would_make_my_life_amazing()

    # I get goosebumps just thinking about this
    main(*args, **kwargs)
3 Answers
Related