Many languages include an integer/float clamp (or clip) function. It’s used to impose an upper and lower limit.
Rust implemented it in their
num crate, and c++ (17) has it in their
Personally, I’d stick it in the Math module, but that’s not important now. Below are 2 common implementation.
def clamp(n, lower, upper): return sorted([lower, n, upper]) # or maybe def clamp(n, lower, upper): return min(max(n, lower), upper)
- A Pythonic clamp was discussed on SO.
- It’s already implemented in many popular libraries (like PyTorch, NumPy), as well as a lightweight PIP packaged called
clip_values, which demonstrate the “need” for a standard lib implementation.
- Against The function would be sparsely used/is easily writable as needed
- Against As previously stated, multiple implementations are already been made and can be pip installed.
In all seriousness, I think this would be an easy and widely used function.