Next / Previous / Contents / Shipman's homepage

18.3. Args._checkPositive(): Check for a positive integer

listext2
# - - -   A r g s . _ c h e c k P o s i t i v e

    def _checkPositive(self, rawValue):
        '''Require a positive integer.

          [ rawValue is a str ->
              if rawValue represents a positive int ->
                return that value as an int
              else -> raise argparse.ArgumentTypeError ]
        '''
        #-- 1
        # [ if rawValue can be converted to int ->
        #     return rawValue converted to int
        #   else -> raise argparse.ArgumentTypeError ]
        try:
            value = int(rawValue)
        except ValueError:
            raise argparse.ArgumentTypeError("Must be "
                "a positive integer.")

        #-- 2
        if value < 1:
            raise argparse.ArgumentTypeError("Must be "
                "a positive integer.")
        else:
            return value