
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). My point is that all parameters must be mandatory. Victor Le 31 juil. 2016 6:41 AM, "David Mertz" <mertz@gnosis.cx> a écrit :
Is there some special subtlety or edge case where a hand rolled function will go wrong? I like the SO version spelled like this (a little fleshed out):
def clamp(val, min_val=None, max_val=None): min_val = val if min_val is None else min_val max_val = val if max_val is None else max_val assert min_val <= max_val return max(min(val , max_val), min_val)
On Sat, Jul 30, 2016 at 2:57 PM, Neil Girdhar <mistersheik@gmail.com> 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-pyth...
http://stackoverflow.com/questions/4092528/how-to-clamp-an-integer-to-some-r...
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
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th.
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/