Next / Previous / Contents / Shipman's homepage

11. sizeConverter(): Check the size option

deduper
# - - -   s i z e C o n v e r t e r

def sizeConverter(arg):
    '''Process the size argument.  This interface follows the model
       for the 'type=...' keyword argument to ArgumentParser.add_args().

      [ arg is a str ->
          if arg is a valid size argument ->
            return the equivalent int
          else -> raise argparse.ArgumentTypeError ]
    '''

For the regular expression we use to check the syntax of this argument, see Section 8, “Manifest constants”.

deduper
    #-- 1
    # [ if arg matches SIZE_RE ->
    #     number  :=  the numeric part as a float
    #     suffix  :=  the suffix part as a str
    #   else -> raise argparse.ArgumentTypeError ]
    m = SIZE_RE.match(arg)
    if m is None:
        raise argparse.ArgumentTypeError("Invalid size argument "
            "{0!r}".format(arg))
    number = float(m.group(NUMBER_GROUP))
    suffix = m.group(SUFFIX_GROUP).upper()

For the table of suffix values, see Section 8, “Manifest constants”.

deduper
    #-- 2
    # [ if suffix, upshifted, is a key in SIZE_CODE_MAP ->
    #     return int(number * (the related value))
    #   else -> raise argparse.ArgumentTypeError ]
    try:
        weight = SIZE_CODE_MAP[suffix]
        return int(number*weight)
    except KeyError:
        raise argparse.ArgumentTypeError("Invalid size suffix: "
            "{0!r}".format(suffix))