Skip to content

Instantly share code, notes, and snippets.

@ydm
Created October 25, 2013 08:57
Show Gist options
  • Select an option

  • Save ydm/7151693 to your computer and use it in GitHub Desktop.

Select an option

Save ydm/7151693 to your computer and use it in GitHub Desktop.
Java's Observer and Observable translated to Python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import threading
class Observer(object):
def update(self, o, *args, **kwargs):
"""
This method is called whenever the observed object is changed
Arguments:
o - observable
args and kwargs - any arguments supplied by the observed object
"""
pass
class Observable(object):
def __init__(self):
self._changed = False
self._lock = threading.Lock()
self._obs = set()
def add_observer(self, o):
with self._lock:
self._obs.add(o)
def delete_observer(self, o):
with self._lock:
self._obs.remove(o)
def notify_observers(self, *args, **kwargs):
with self._lock:
if not self._changed:
return
self.clear_changed()
snapshot = self._obs.copy()
for obs in snapshot:
obs.update(*args, **kwargs)
def delete_observers(self):
with self._lock:
self._obs.clear()
def set_changed(self):
with self._lock:
self._changed = True
def clear_changed(self):
with self._lock:
self._changed = False
def has_changed(self):
with self._lock:
return self._changed
def count_observers(self):
with self._lock:
return len(self._obs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment