Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python optparse, default values for optional options

This is more like a code design question. what are good default values for optional options that are of type string/directory/fullname of files?

Let us say I have code like this:

import optparse
parser = optparse.OptionParser()
parser.add_option('-i', '--in_dir', action = "store", default = 'n', help = 'this is an optional arg')
(options, args) = parser.parse_args()  

Then I do:

if options.in_dir == 'n':
    print 'the user did not pass any value for the in_dir option'
else:
    print 'the user in_dir=%s' %(options.in_dir)

Basically I want to have default values that mean the user did not input such option versus the actual value. Using 'n' was arbitrary, is there a better recommendation?

like image 215
Dnaiel Avatar asked Dec 22 '13 22:12

Dnaiel


People also ask

Is Optparse deprecated?

Deprecated since version 3.2: The optparse module is deprecated and will not be developed further; development will continue with the argparse module. optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module.

What does Parse_args return?

parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.

How do you add options in Python?

Defining options: It should be added one at a time using the add_option(). Each Option instance represents a set of synonymous command-line option string. To define an option with only a short option string: parser.

What does Options do in Python?

options inquires as to how many parameters the callable accepts. If it accepts only 1, it will be the value passed in.


2 Answers

You could use an empty string, "", which Python interprets as being False; you can simply test:

if options.in_dir:
    # argument supplied
else:
    # still empty, no arg

Alternatively, use None:

if options.in_dir is None:
    # no arg
else:
    # arg supplied 

Note that the latter is, per the documentation the default for un-supplied arguments.

like image 81
jonrsharpe Avatar answered Sep 17 '22 23:09

jonrsharpe


How about just None?

Nothing mandates that the default values must be of the same type as the option itself.

import optparse
parser = optparse.OptionParser()
parser.add_option('-i', '--in_dir', default=None, help='this is an optional arg')
(options, args) = parser.parse_args()  
print vars(options)

(ps. action="store" isn't required; store is the default action.)

like image 30
AKX Avatar answered Sep 21 '22 23:09

AKX