Since this thing is on the innerwebs I suppose it should have a
[python_utils.git] / type / rate.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """A class to represent a rate of change."""
6
7 from typing import Optional
8
9
10 class Rate(object):
11     """A class to represent a rate of change."""
12
13     def __init__(
14         self,
15         multiplier: Optional[float] = None,
16         *,
17         percentage: Optional[float] = None,
18         percent_change: Optional[float] = None,
19     ):
20         count = 0
21         if multiplier is not None:
22             if isinstance(multiplier, str):
23                 multiplier = multiplier.replace('%', '')
24                 m = float(multiplier)
25                 m /= 100
26                 self.multiplier: float = m
27             else:
28                 self.multiplier = multiplier
29             count += 1
30         if percentage is not None:
31             self.multiplier = percentage / 100
32             count += 1
33         if percent_change is not None:
34             self.multiplier = 1.0 + percent_change / 100
35             count += 1
36         if count != 1:
37             raise Exception('Exactly one of percentage, percent_change or multiplier is required.')
38
39     def apply_to(self, other):
40         return self.__mul__(other)
41
42     def of(self, other):
43         return self.__mul__(other)
44
45     def __float__(self):
46         return self.multiplier
47
48     def __mul__(self, other):
49         return self.multiplier * float(other)
50
51     __rmul__ = __mul__
52
53     def __truediv__(self, other):
54         return self.multiplier / float(other)
55
56     def __add__(self, other):
57         return self.multiplier + float(other)
58
59     __radd__ = __add__
60
61     def __sub__(self, other):
62         return self.multiplier - float(other)
63
64     def __eq__(self, other):
65         return self.multiplier == float(other)
66
67     def __ne__(self, other):
68         return not self.__eq__(other)
69
70     def __lt__(self, other):
71         return self.multiplier < float(other)
72
73     def __gt__(self, other):
74         return self.multiplier > float(other)
75
76     def __le__(self, other):
77         return self < other or self == other
78
79     def __ge__(self, other):
80         return self > other or self == other
81
82     def __hash__(self):
83         return self.multiplier
84
85     def __repr__(self, *, relative=False, places=3):
86         if relative:
87             percentage = (self.multiplier - 1.0) * 100.0
88         else:
89             percentage = self.multiplier * 100.0
90         return f'{percentage:+.{places}f}%'