Skip to content

Instantly share code, notes, and snippets.

@objarni
Forked from Neppord/alarm.py
Created September 14, 2012 06:25
Show Gist options
  • Save objarni/3720182 to your computer and use it in GitHub Desktop.
Save objarni/3720182 to your computer and use it in GitHub Desktop.
fuse variation
import random
class Sensor(object):
OFFSET = 16
def pop_next_pressure_psi_value(self):
pressure_telemetry_value = self.sample_pressure()
return Sensor.OFFSET + pressure_telemetry_value
def __iter__(self):
return iter(self.pop_next_pressure_psi_value, Ellipsis)
@staticmethod
def sample_pressure():
# placeholder implementation that simulate a real sensor in a real tire
pressure_telemetry_value = 6 * random.random() * random.random()
return pressure_telemetry_value
class TirePressureAlarm():
def __init__(self):
self.fuse = Fuse(
condition=lambda value : not 17 <= value <= 21,
iterator=iter(Sensor())
)
def check(self):
self.fuse.check()
def is_alarm_on(self):
return self.fuse.on
Alarm = TirePressureAlarm
class Fuse(object):
def __init__(self, condition, iterator):
self.__conditon = condition
self.__iterator = iterator
self.__on = False
def check(self):
value = self.__iterator.next()
self.__on = self.on or self.__conditon(value)
@property
def on(self):
return self.__on
@magnus-lycka
Copy link

Why "self.__on = self.on or self.__conditon(value)"? Why not "self.__on = self.__on or self.__conditon(value)"?
Are you expecting a sub class to return anything else than self.__on from self.on?

@objarni
Copy link
Author

objarni commented Sep 18, 2012

Oh I missed all these comments until now! (why doesn't github notify me when ppl comment on my gist?). I just read about the single/double underscore in docs, maybe single underscore is a little more "agile" since double underscores kind of assumes you are subclassing (it does some naming magic wizardry which I didn't quite follow..). Single _underscore convention just means " these members are subject to API changes without notice". [everything is a convention no real private vars in Python that I know of..]

@emilybache
Copy link

Thanks for finding the docs, Andre. So even __ is not really private, you can still get at it from the outside. So the convention is to use _ most of the time, and __ when that doesn't work. So I think in this code, single underscores would work fine.

@Neppord
Copy link

Neppord commented Sep 27, 2012

@emilybache i do agree that _ is enough though I think that the "you can still get to it" is the wrong reason. Unless you think privat in Java is not private, since you can get to that with reflections...

Any mays, i have ssen that you changed it in your code, but you made the alarm_on method only a public variable, letting the interface the user change the value and not only read it. And also i though that the Java-nes of the code was quite fun to pythonify.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment