Next / Previous / Contents / Shipman's homepage

15. argPair(): Process one or two arguments

Several methods of this package operate on pairs of values that can be specified as either two positional arguments, or one positional argument that can be iterated to extract two values from it.

This function accepts one or two positional arguments and returns a 2-tuple containing the two values. Additionally, if the argument is iterable but contains only one value, it returns a 2-tuple containing two copies of the value.
# - - -   a r g P a i r

def argPair(*p):
    '''Process a pair of values passed in various ways.

      [ if len(p) is 2 ->
            return (p[0], p[1])
        else if p is a single non-iterable ->
          return (p[0], p[0])
        else if p is an iterable with two values ->
            return (p[0][0], p[0][1])
        else if p is an iterable with one value ->
            return (p[0][0], p[0][0])
    #-- 1 --
    if len(p) == 2:
        return (p[0], p[1])

    #-- 2 --
    it = p[0]
    if not hasattr(it, "__iter__"):
        return(it, it)

    #-- 3 --
    # [ p is an iterable ->
    #     values  :=  all values from p[0] ]
    values = [ x
               for x in p[0] ]

    #-- 4 --
    if len(values) == 1:
        return (values[0], values[0])
        return (values[0], values[1])