fluttersmith/py-snippetsGitHub ↗

Clamp a number to a range

Limit a value to an inclusive range, accepting the bounds in either order.

Numbers#validationO(1) time✓ 3 examples pass on 3.11–3.14

Keep a volume between 0 and 100, or a page number inside the document.

clamp_number.py✓ ruff · mypy --strict
def clamp_number(value: float, low: float, high: float) -> float:
    """Limit ``value`` to the range between ``low`` and ``high``, inclusive."""
    low, high = min(low, high), max(low, high)
    return max(low, min(value, high))
  1. sort the bounds so callers can't get them backwards
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> clamp_number(2, 3, 5)3passed on Python 3.11 to 3.14: >>> clamp_number(1, -1, -5)-1passed on Python 3.11 to 3.14: >>> clamp_number(4.5, 0, 10)4.5
Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).

How it works

  • min(value, high) caps the top; max(low, ...) lifts the bottom.
  • The bounds are sorted first, so clamp_number(x, 10, 0) works too.
  • Ints stay ints and floats stay floats.

Complexity: O(1) time and space

Importfrom pysnippets.numbers.clamp_number import clamp_numberNo dependencies: copy clamp_number.py into your project, or clone the repo.

Adapted from clamp-number in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed; clearer names. Suggest an edit.