Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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