Last active
December 29, 2016 04:15
-
-
Save Mekire/b3962cdbd5062ce8c461c8497a754680 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import division | |
class BoundedFloat(float): | |
def __new__(self, value, minimum, maximum): | |
return float.__new__(self, value) | |
def __init__(self, value, minimum, maximum): | |
if not (minimum <= value <= maximum): | |
raise ValueError("Minimum must be less than or equal to value which" | |
" must be less than or equal to maximum.") | |
float.__init__(value) | |
self.minimum = minimum | |
self.maximum = maximum | |
@classmethod | |
def _limit_inplace_ops(cls): | |
limit_ops = ["__iadd__", "__isub__", "__imul__", "__itruediv__", | |
"__ifloordiv__", "__ipow__", "__imod__"] | |
for op in limit_ops: | |
setattr(cls, op, cls._limit(getattr(cls, op.replace("i", "", 1)))) | |
@classmethod | |
def _limit(cls, function): | |
def wrapped(self, other): | |
new = function(self, other) | |
if new < self.minimum: | |
result = BoundedFloat(self.minimum, self.minimum, self.maximum) | |
elif new > self.maximum: | |
result = BoundedFloat(self.maximum, self.minimum, self.maximum) | |
else: | |
result = BoundedFloat(new, self.minimum, self.maximum) | |
return result | |
return wrapped | |
BoundedFloat._limit_inplace_ops() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment