From b4874d3088119d4dbe85e86ebecc268ed5cd88c9 Mon Sep 17 00:00:00 2001 From: Ben Elliston Date: Sat, 14 Dec 2024 14:28:40 +1100 Subject: [PATCH] * nemo/utils.py (MultiSetter): New class. --- nemo/utils.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/nemo/utils.py b/nemo/utils.py index c290368a..6f863317 100644 --- a/nemo/utils.py +++ b/nemo/utils.py @@ -43,6 +43,35 @@ register_matplotlib_converters() +class MultiSetter: + """A setter that broadcasts its value to any number of setters. + + This is useful for generator pairs such as a Battery and a + BatteryLoad, where there should only be one (tied) capacity for + both objects. + + >>> setter1 = (lambda x: print("one", x), 0, 40) + >>> setter2 = (lambda x: print("two", x), 0, 40) + >>> ds = DualSetter(setter1, setter2) + >>> ds.set_capacity(1.2) + one 1.2 + two 1.2 + """ + + def __init__(self, *args): + """Initialise a MultiSetter with any number of setters.""" + self.setters = [] + for setter in args: + if not callable(setter): + raise TypeError + self.setters.append(setter[0]) + + def set_capacity(self, value): + """Broadcast value to all setters.""" + for setter in self.setters: + setter(value) + + def thousands(value): """Format a value with thousands separator(s).