[Python-ideas] Consider adding clip or clamp function to math

Steven D'Aprano steve at pearwood.info
Sun Jul 31 22:47:39 EDT 2016

On Sun, Jul 31, 2016 at 09:38:44PM +0200, Victor Stinner wrote:
> I dislike this API. What's the point of calling clamp(x)? clamp(b, a) is
> min(a, b) and clamp(a, max_val=b) is just max(a, b). 

You have that the wrong way around. If you supply a lower-bounds, you 
must take the max(), not the min(). If you supply a upper-bounds, you 
take the min(), not the max(). It's easy to get wrong.

> My point is that all parameters must be mandatory.

I don't care too much whether the parameters are mandatory or have 
defaults, so long as it is *possible* to pass something for the lower 
and upper bounds which mean "unbounded". There are four obvious 
alternatives (well three obvious ones and one surprising one):

(1) Explicitly pass -INFINITY or +INFINITY as needed; but which 
infinity, float or Decimal? If you pass the wrong one, you may have to 
pay the cost of converting your values to float/Decimal, which could end 
up expensive if you have a lot of them.

(2) Pass a NAN as the bounds. With my implementation, that actually 
works! But it's a surprising accident of implementation, it feels wrong 
and looks weird, and again, it may require converting the values to 

(3) Use some special Infimum and Supremum objects which are smaller 
than, and greater than, every other value. But we don't have such 
objects, so you'd need to create your own.

(4) Use None as a placeholder for "no limit". That's my preferred 

Of course, even if None is accepted as "no limit", the caller can still 
explicitly provide an infinity if they prefer.

As I said, I don't particularly care whether the lower and upper bounds 
have default values. But I think it is useful and elegant to accept None 
(as well as infinity) to mean "no limit".


More information about the Python-ideas mailing list