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

Neil Girdhar mistersheik at gmail.com
Sat Jul 30 18:02:18 EDT 2016


Rather:

assert lower <= upper

And apologies if this has been requested before.  My search turned up 
nothing.


On Saturday, July 30, 2016 at 5:57:53 PM UTC-4, Neil Girdhar wrote:
>
> It's common to want to clip (or clamp) a number to a range.  This feature 
> is commonly needed for both floating point numbers and integers:
>
>
> http://stackoverflow.com/questions/9775731/clamping-floating-numbers-in-python
>
> http://stackoverflow.com/questions/4092528/how-to-clamp-an-integer-to-some-range-in-python
>
> There are a few approaches: 
>
> * use a couple ternary operators (e.g. 
> https://github.com/scipy/scipy/pull/5944/files  line 98, which generated 
> a lot of discussion)
> * use a min/max construction,
> * call sorted on a list of the three numbers and pick out the first, or
> * use numpy.clip. 
>
> Am I right that there is no *obvious* way to do this?  If so, I suggest 
> adding math.clip (or math.clamp) to the standard library that has the 
> meaning:
>
> def clip(number, lower, upper):
>     return lower if number < lower else upper if number > upper else number
>
> This would work for non-numeric types so long as the non-numeric types 
> support comparison.  It might also be worth adding
>
> assert lower < upper
>
> to catch some bugs.
>
> Best,
>
> Neil
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160730/8073309b/attachment.html>


More information about the Python-ideas mailing list