Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Last active February 5, 2022 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/80dc86619ca79ffd0b24ba8f0fb309e1 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/80dc86619ca79ffd0b24ba8f0fb309e1 to your computer and use it in GitHub Desktop.
Generic number clipping function. Works with mypy type annotations.
from numbers import Number
from typing import TypeVar
N = TypeVar("N", bound=Number)
"""A number; e.g. either float or int.
"""
def clip(value: N, minimum: N, maximum: N) -> N:
"""Bounds the `value` to [`minimum`,`maximum`].
"""
max_clip: N = min(value, maximum)
min_clip: N = min(max_clip, minimum)
return min_clip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment