Even after years of coding it sometimes takes me a moment to
correctly parse expressions like `min(max(value, minimum),
maximum)`, especially when the parentheses enclose some local
computation instead of only references, and the fact that `min`
actually needs the *maximum* value as an argument (and vice-versa)
certainly doesn't help.
It's a little surprising to me how shorthand functions akin to CSS's `clamp()` aren't more popular among modern programming languages. Such a tool is, in my opinion, even more missed in Python, what with it being focussed on readability and all. There would likely also be some (probably minor) performance advantages with implementing it at a builtins level.
Example usage:
>>> val = 100 >>> clamp(10, val, 50) 50 >>> val = 3 >>> clamp(10, val, 50) 10 >>> val = 25 >>> clamp(10, val, 50) 25
I'm undecided whether I would like `clamp`, `minmax` or something else as a name. I'm curious of other ideas.
As far as the signature is concerned, I like both `clamp(min,
val, max)` for the logical position of the three arguments (which
mirrors expressions such as `min < val < max`) and
`clamp(val, min=x, max=y)`. I prefer the former, but declaring
them as normal positional-and-keyword arguments would allow the
programmer to use an alternative order if they so choose.