pythonoptparse

Triggering callback on default value in optparse


I'm using Python's optparse to do what it does best, but I can't figure out how to make the option callback trigger on the default argument value if no other is specified via command-line; is this even possible? This would make my code much cleaner.

I can't use argparse unfortunately, as the platform I'm running on has an outdated Python version.

Edit: To provide more detail, I'm adding an option with a callback and a default value

parser.add_option(
  "-f",
  "--format",
  type = "string",
  action = "callback",
  callback = format_callback,
  default = "a,b,c,d")

The callback function is defined as follows:

def format_callback(option, opt, value, parser):
  # some processing
  parser.values.V = processed_value

Basically I'm processing the "--format" value and putting the result into the parser. This works fine, when "--format" is specified directly via command-line, but I'd like the callback to be triggered on the default "a,b,c,d" value as well.


Solution

  • It is simply not possible.

    The optparse.OptionParser implementation of parse_args starts with:

    def parse_args(self, args=None, values=None):
        """
        parse_args(args : [string] = sys.argv[1:],
                   values : Values = None)
        -> (values : Values, args : [string])
    
        Parse the command-line options found in 'args' (default:
        sys.argv[1:]).  Any errors result in a call to 'error()', which
        by default prints the usage message to stderr and calls
        sys.exit() with an error message.  On success returns a pair
        (values, args) where 'values' is an Values instance (with all
        your option values) and 'args' is the list of arguments left
        over after parsing options.
        """
        rargs = self._get_args(args)
        if values is None:
            values = self.get_default_values()
    

    Default values are set before processing any arguments. Actual values then overwrite defaults as options are parsed; the option callbacks are called when a corresponding argument is found.

    So callbacks simply cannot be invoked for defaults. The design of the optparse module makes this very hard to change.