[Python-ideas] Consider adding clip or clamp function to math
David Mertz
mertz at gnosis.cx
Sun Jul 31 16:16:55 EDT 2016
On Sun, Jul 31, 2016 at 12:38 PM, Victor Stinner <victor.stinner at gmail.com>
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). My point is that all
> parameters must be mandatory.
>
Fair enough. I was envisioning a usage like:
bottom, top = None, None
# ... some code that might derive values for bottom and/or top
x = clamp(x, bottom, top)
But this also lets us use the same signature for, e.g.:
y = clamp(y, max_val=100)
Still, my point wasn't to argue for a signature or implementation, but just
opining that the utility is easy enough to write that users can put it in
their own library/code.
Le 31 juil. 2016 6:41 AM, "David Mertz" <mertz at 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 at gmail.com>
>> wrote:
>>
>>> 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:
>>>
>>
--
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160731/28542d1b/attachment.html>
More information about the Python-ideas
mailing list