python optparse, default values for optional options

optparse, python

Solution

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.

Problem

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?

Original source