Next / Previous / Contents / Shipman's homepage

18. class Args: Command line arguments

This class represents the digested and checked command line arguments. It is a singleton: the first time the constructor is called, the command line arguments are checked and digested and, if valid, made into an instance of the class. Any successive calls will return the same instance.

Here is the interface to the class. For the specification of the command line arguments and defaults, see Section 3, “Operation of the listext2 script”.

listext2
# - - - - -   c l a s s   A r g s

class Args(Singleton):
    '''Represents our command line arguments.

      Exports:
        Args():
          [ if the command line arguments are valid ->
              return the singleton instance of self representing
              those arguments
            else ->
              sys.stderr  +:=  usage and error messages
              stop execution ]
        .inFileName:    [ name of the input file ]
        .inFile:        [ input file, opened for reading ]
        .pointSize:     [ font size in points as a positive int ]
        .extraLeading:  [ leading as an h.FoDim instance ]
        .tabSize:       [ tab size as a positive int ]
        .nCols:         [ number of columns as a positive int ]
        .outFileName:   [ output file name as a str ]
        .breakString:   [ breakstring as a str ]
        .isLandscape:   [ True if landscape, else False or None ]
        .duplex:        [ True if 2-sided, False for 1-sided ]

      State/Invariants:
        .rawLeading:    [ effective leading option as a string ]
        ._argParser:
          [ an argparse.ArgumentParser instance ]
    '''

The class variable INITIALIZED prevents the constructor from re-parsing the options every time there is a reference to Args().

listext2
    INITIALIZED = False

The class variables below specify default option values. DEFAULT_LEADING_INCR is not the default value; it is the default increment added to the effective font size.

listext2
    DEFAULT_POINT_SIZE = 8
    DEFAULT_LEADING_INCR = h.FoDim("1.0", "pt")
    DEFAULT_TAB_SIZE = 4
    DEFAULT_LANDSCAPE_COLS = 2
    DEFAULT_PORTRAIT_COLS = 1
    DEFAULT_OUT_FILE = 'klarn.fo'
    DEFAULT_BREAK_STRING = '\f'
    DEFAULT_IS_LANDSCAPE = True
    DEFAULT_DUPLEX = True

18.1. Args.__init__()

Command line arguments are processed in two stages. General checking of arguments is handled by the standard Python argparse module. Further checks specific to this program, and the setting of some final values, are done in Section 18.5, “Args._final(): Semantic checking”.

Most of our attributes are set directly by the argparse module. However, there are three exceptions.

  • The value of self.extraLeading is not the value of the --lead argument; it is the effective leading minus the effective point size. Hence this must be computed after argparse determines the effective point size. The value of the --lead option, if given, is routed to self.rawLeading.

  • The default value of self.nCols is 1 for portrait, 2 for landscape. Hence argparse is instructed to use None as the default value so we can tell whether an explicit value was given. The final value is computed in Section 18.5, “Args._final(): Semantic checking”.

  • The --portrait and --landscape options are mutually exclusive; we use the group feature of argparse to enforce this. The destination for both options is self.isLandscape.

If the constructor has already been called at least once, self.INITIALIZED will be True. This prevents the arguments from being re-parsed at every reference to Args().

listext2
# - - -   A r g s . _ i n i t _ _

    def __init__(self):
        '''Constructor.
        '''
        #-- 1
        if self.INITIALIZED: return
        else:                self.INITIALIZED = True

For the setup of the ArgumentParser, see Section 18.2, “Args.__parse(): Option syntax checking”.

listext2
        #-- 2
        # [ self._argParser  :=  an argparse.ArgumentParser instance that
        #       routes all option values to the corresponding
        #       attribute of self, except that --lead is routed to
        #       self.rawLeading ]
        self._buildParser()

        #-- 3
        # [ if sys.argv is valid according to self._argParser ->
        #     self  :=  self with option values routed to the
        #         corresponding attributes of self, except --lead
        #         is routed to self.rawLeading
        #   else ->
        #     sys.stderr  +:=  error and usage messages
        #     stop execution ]
        try:
            self._argParser.parse_args(namespace=self)
        except IOError as x:
            print("Can't open the input file: {0}".format(
                  str(x)), file=sys.stderr)
            sys.exit(1)

For final option value computation, see Section 18.5, “Args._final(): Semantic checking”.

listext2
        #-- 4
        # [ self.extraLeading  :=  (effective leading from
        #       self.rawLeading) - (self.pointSize), as an h.FoDim
        #   self.nCols  :=  self.nCols with default value as a
        #       function of self.isLandscape ]
        self._final()