def clamp(val, min_val=None, max_val=None):
# swap min and max if wrong way round.
if min_val is not None and max_val is not None and max_val < min_val:
min_val, max_val = max_val, min_val
if min_val is not None:
val = max([val, min_val])
if max_val is not None:
val = min([val, max_val])
return val