Every 15 seconds, or when the potato color changes, I want to print potato.color
.
How can I monitor the potato color changes event without a setter function?
There is a way to do this with an Observer pattern How to trigger function on value change?
which uses a setter and a mysterious callback.
Now, from the potato color setter set_color
, I could call the event_publisher everytime. The problem is, that the potato.color is usually just set with
potato.color = "poison-green"
, and I can't prevent people from setting the color that way.
Now what this code does:
Potato.set_color
is never called, because the programmer was silly. But could be used for the observer_pattern, and everytime the value is set again, we callevent_publisher
. Problem: The programmer was silly, and is unused.frequency_publisher
prints every 15 secondsevent_publisher is supposed to monitor the own class, and call the event_publisher whenever the self.color changes. My favorite solution, because refactoring the code to call set_color is difficult.
Is there a way to write either the event_publisher outside the function, or the my_color_changed_event function?
import asyncio
import random
class Potato:
color = "potato-yellow"
def set_color(self, color_):
# Is there a way around this?
# Someone could just set potato.color = "green" without calling this setter
self.color = color_
event_publisher(self)
async def my_color_changed_event(self):
while True:
if random.randint(1, 100) < 30: # PLACEHOLDER FOR if self.color changed???
await asyncio.sleep(5)
return True
return False
async def frequency_publisher(potato_):
while True:
print("Publish by time!", potato_.color)
await asyncio.sleep(15)
async def event_publisher(potato_):
while True:
# Somehow watch potato_ for changes
# ???
event_ = await potato_.my_color_changed_event(potato_)
if event_:
print("Publish by event!", potato_.color)
if __name__ == '__main__':
potato = Potato
while True:
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
event_publisher(potato),
frequency_publisher(potato)
))
except KeyboardInterrupt:
break