gratchie
gratchie

Reputation: 13

Argument checks best practices

I have a simple code that needs at least 1 argument. Right now my code format looks something like this:

import modules 

# argparse stuff
parser = argparse.ArgumentParser()
parser.add_argument(-m)
parser.add_argument(-u)
args = parser.parse_args()

# check the number of arguments 
if len(sys.argv) > 3:
sys.exit()

if len(sys.argv) == 1:
sys.exit()

class Program:
      def A():
      def B():
      def C():

if __name__ == '__main__':
    try:
       Program()

The code works as intended, but I'd like to know how I can rewrite my code to be 'pythonic'. Do I put the argument checks under the 'if name' statement? If so, how? thanks.

Upvotes: 0

Views: 1430

Answers (2)

willnx
willnx

Reputation: 1283

I would suggest not looking at sys.argv, especially if you're already using a CLI parsing library.

Argprase has a pile of ways to enforce requirements, but if none of those fit your needs you can looks at your 'args' object.

Personally, I would suggest not running functions, like parse_args(), in the global scope of that file. Instead I would suggest (at minimum) to just wrap what you've got in a function called main, then call 'main()' after 'if __name__ == '__main__'

Argparse examples:

if '-m' and '-u' are mutually exclusive

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-m')
group.add_argument('-u')

args = parser.parse_args()  # will output a error message if '-m' or '-u' isn't supplied

If a specific arg is required always

parser = argparse.ArgumentParser()
parser.add_argument('-m', required=True)   # must always give '-m'

Or just looking at the 'args' object

parser = argparse.ArgumentParser()
parser.add_argument('-m')
parser.add_argument('-u')

args = parser.parse_args()
if not (args.m or args.u):
    sys.exit(1) # should exit non-zero on failures

main wrapping example:

import modules

class Program:
      def A():
      def B():
      def C():

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(-m)
    parser.add_argument(-u)
    args = parser.parse_args()

    if not (args.m or args.u):
        sys.exit(1)

    try:
       Program()
    except SomeException:
        # handle it
        pass # b/c I don't know what you need here

if __name__ == '__main__':
    main()

Upvotes: 1

viraptor
viraptor

Reputation: 34145

Checking the number of arguments after argparse doesn't make much sense. If there's some error, argparse will handle that, so you don't really have to replicate it.

Do put the arguments check after if __name__ check - just in case you want to import the module without executing.

Otherwise, it's just standard code as you'd see in argparse documentation. Nothing really wrong with it.

Upvotes: 0

Related Questions