mvarge
mvarge

Reputation: 324

Optparse and a lot of if not

I'm developing a program that receives some arguments and would like to make some of them required, but I'm steping in some problems:

  1. I really need to make the code Python 2.4.x compliant, so I (at least think that) can only use optparse
  2. Would like to avoid code obscurity

Here's what I made:

def usage():
    parser = OptionParser()
    parser.add_option('-i', '--item', dest='item')
    parser.add_option('-m', '--monitor', dest='monitor')
    parser.add_option('-s', '--service', dest='service')
    parser.add_option('-u', '--status', dest='status')
    parser.add_option('-a', '--match', dest='match')
    parser.add_option('-v', '--value', dest='value')
    parser.add_option('-o', '--hostname', dest='hostname', default='')
    parser.add_option('-t', '--test', action='store_true', dest='test')
    parser.add_option('-U', '--url', dest='URL', default='')
    parser.add_option('--verbose', action='store_true', dest='verbose')

    (options, args) = parser.parse_args()

    if not options.item or not options.monitor or not options.service or \
                           not options.status or not options.match or \
                           not options.value:
        parser.print_help()
        sys.exit(-1)

    return options

I guess this is OK but I really don't think this is Pythonic. Is there a better way for do this condition checking?

Cheers,

Upvotes: 1

Views: 142

Answers (2)

Andrew
Andrew

Reputation: 3061

You could make it a little bit nicer with:

if None in (options.monitor, options.service, options.status, options.match,
             options.value):

But if you are limited to optparse then it is designed to handle optional arguments, there does not seem to be a better way to do it.

Upvotes: 0

Tordek
Tordek

Reputation: 10882

You can define an array of required options, like...

required_options = [options.monitor, options.service, ...]

and check

if not all(required_options):
    ...

Upvotes: 5

Related Questions