2

I have written to following code but it feels very clunky and I was wondering if there was a pythonic way of writing the following code:

import argparse

foo = 0
bar = 1

parser = argparse.ArgumentParser()
parser.add_argument("-a", "--foo", type=int,
                    help="foo")
parser.add_argument("-b", "--bar", type=int,
                    help="bar")

args = parser.parse_args()
if args.foo:        # This is the bit that I think is clunky
    foo = args.foo  #
if args.bar:        #
    bar = args.bar  #

In my code I have about 7 different arguments and having a list of if statements doesn't seem like the best method. Is there a better way of writing this section?

sunny
  • 530
  • 1
  • 6
  • 12

2 Answers2

3

argparse have default arguments, so there is no need for the ifs. Also, you should seperate argument parsing and processing, therefore you don't need local variables for your args, but can use them as parameters. So you would finally get to something like this:

import argparse

def some_function(foo, bar):
    pass

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--foo", type=int, default=0,
                        help="foo")
    parser.add_argument("-b", "--bar", type=int, default=1,
                        help="bar")

    args = parser.parse_args()
    some_function(args.foo, args.bar)


if __name__ == '__main__':
    main()
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Similar questions and answers: http://stackoverflow.com/questions/24127388/python-argparse-how-to-refer-args-by-their-name/ and http://stackoverflow.com/questions/8306171/python-extract-variables-out-of-namespace/ – hpaulj Dec 20 '14 at 20:38
1

In argsparse there are default and required fields that can help you reduce the amount of if's you have.

Example:

parser = argparse.ArgumentParser()
parser.add_argument("-a", "--foo", type=int, required=True,
                    help="foo")
parser.add_argument("-b", "--bar", type=int, default=42,
                    help="bar")

You can also return the args object, and accessing the args at a later point.

Udy
  • 2,492
  • 4
  • 23
  • 33