Math.Clamp/Clip proposal

Clamp/Clip proposal

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 algorithm package.

Possible Py implementations

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])[1]
	
# or maybe

def clamp(n, lower, upper):
  return min(max(n, lower), upper)

Previous discussions within the community

  • 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.

Possible arguments against the “proposal”

  • 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.

Adding a single function does not require a PEP.

Lol I figured as much, sorry for the bad joke. I’ll remove it

Edit: math — Mathematical functions — Python 3.10.4 documentation I’m not sure where I could find these sorts of functions in the source. I’d like to look how they were implemented and maybe make a PR.

The math module is implemented in C. You can find it here.

Oh, interesting. Thank you for the link. I can’t even deduce how floor() or ceil() are created, it looks like part of it is actually a comment? Weird. I hoped at least part of it was extendable by Py code

See previous discussions here: Mailman 3 Consider adding clip or clamp function to math - Python-ideas - python.org

1 Like

Thank you, Mark. I’m embarrassed I missed that during my own research. After reading through the thread, I understand the hesitation to implement it.