New restrain builtin function?

Pierre Rouleau prouleau at impathnetworks.com
Sat Mar 20 15:22:58 EST 2004


Hi all,

In several occasions, I found myself looking for a function that would 
take a value and restrict is within a specified set of boundaries.   For 
a 1-dimension value, I could simply write

	min(max(value,theMin),theMax)

to restrict value within the range made of theMin to theMax.
It assumes that theMax >= theMin.

I was looking for a single call to restrict a value within bounds that 
would do pretty much that, so i wrote this trivial one:

def restrain(value, theMin, theMax) :
     """Return a value that is in restricted to the [theMin, theMax] range.

     **Example**

     >>> for val in xrange(-1,7,1):
     ...   print "restrain(%d,1,5) = %d" % (val, restrain(val,1,5))
     ...
     restrain(-1,1,5) = 1
     restrain(0,1,5) = 1
     restrain(1,1,5) = 1
     restrain(2,1,5) = 2
     restrain(3,1,5) = 3
     restrain(4,1,5) = 4
     restrain(5,1,5) = 5
     restrain(6,1,5) = 5
     >>>
     """

     assert(theMax >= theMin)
     return min(max(value,theMin),theMax)


Without the assertion check, the restrain() named function runs 
expectedly slower than the explicit min(max()) calls:

C:\Python23\Lib>timeit "min(max(5,1),0)"
1000000 loops, best of 3: 1.02 usec per loop

C:\Python23\Lib>timeit -s"from ut import restrain" "restrain(5,1,6)"
1000000 loops, best of 3: 1.53 usec per loop

Again, I found myself writing code that has to restrain the values to 
some range and prefer using the restrain() function instead of the 
min(max()) one.

Therefore, I was wondering if it would it make sense to add a function 
like restrain() to the list of Python built-ins.  Or is there something 
like that already in the Python library?


Thanks

Pierre








More information about the Python-list mailing list