def closestDistanceToRegion(reference, position1, position2=None,
    zero_inside_region=False):
    """Return distance from a reference position to a coordinate or region

    For a single specified position, return the absolute distance between
    that position and the reference point.
        
    If a second position is given (specifying a region) then return the
    smallest absolute distance of (reference,position1) and
    (reference,position2).
        
    By default there is no special treatment when the reference lies inside
    the region specified by two positions; to return zero distance in
    these cases, set the 'zero_inside_region' argument to True.
    """
    if position2 is None:
        return abs(reference - position1)
    if zero_inside_region:
        if position1 < position2:
            upper, lower = position2, position1
        else:
            upper, lower = position1, position2
        if lower < reference and reference < upper:
            return 0
    return min(abs(reference - position1), abs(reference - position2))
