14

Is there anything inherently wrong with getting command-line arguments in this way? I mean by putting the argument parsing into its own function. Would it be considered non-Pythonic or more so?

#!/usr/bin/python

import argparse

def getArgs(argv=None):
    parser = argparse.ArgumentParser(description="calculate X to the power of Y")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", "--verbose", action="store_true")
    group.add_argument("-q", "--quiet", action="store_true")
    parser.add_argument("x", type=int, help="the base")
    parser.add_argument("y", type=int, help="the exponent")
    return parser.parse_args(argv)

if __name__ == "__main__":

    argvals = None             # init argv in case not testing
    argvals = '6 2 -v'.split() # example of passing test params to parser
    args = getArgs(argvals)

    answer = args.x**args.y

    if args.quiet:
        print answer
    elif args.verbose:
        print "{} to the power {} equals {}".format(args.x, args.y, answer)
    else:
        print "{}^{} == {}".format(args.x, args.y, answer)
3
  • 1
    Nope, that's just fine. Commented Nov 6, 2014 at 17:45
  • You could use a single option for verbosity but, as you have 3 levels of it, it may not be more comprehensible. Commented Nov 6, 2014 at 18:01
  • @ivan_pozdeev - Thanks for the feedback about the verbosity. The base example comes from docs.python.org/2/howto/argparse.html#conflicting-options. Was really asking about putting the argparse block inside a function as opposed to it being 'naked'. Seems to me my example is more Pythonic but I could not locate any examples of anyone else doing it. Hence my question. Commented Nov 6, 2014 at 18:21

2 Answers 2

11

It looks good, feels good, conforms to Python Zen - so, what's the problem if you didn't see this particular code like that?

Moving a somewhat independent piece of functionality into a subroutine is essential good practice - a manifestation of separation of concerns, to be precise. It's not even about Python.

Sign up to request clarification or add additional context in comments.

1 Comment

Accepted this answer as it confirms the philosophy. Thanks, @ivan_pozdeev!
8

This is fine. The only suggestion I would make is to allow get_args to take as a parameter (None by default) a list of arguments to pass to parse_args(). This makes testing easier. Also, the import statement should still go at the top of the script, not inside get_args itself.

import argparse

# ...

def get_args(argv=None):
    parser = argparse.ArgumentParser(description="calculate X to the power of Y")
    # ...
    return parser.parse_args(argv)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.