Skip to content

Instantly share code, notes, and snippets.

@n1ywb
Created January 2, 2013 15:55
Show Gist options
  • Save n1ywb/4435504 to your computer and use it in GitHub Desktop.
Save n1ywb/4435504 to your computer and use it in GitHub Desktop.
Non-functional concept of the observer pattern for Twisted python objects using descriptors and metaclasses.
lass DataObject(object):
def to_html(self, updated_station):
self.html = "whatever"
self.on_html_update.callback(self.html)
def update(self, updated_stations):
self.json = self.to_json(updated_stations)
self.on_json_update.callback(self.json)
class ObservableField(object):
def __get__(self, instance, owner):
# return deferred; wait what about sync clients? when to FIRE deferred?
def __set__(self, instance, value):
class DataObjectMeta(object):
def __new__(klass, name, bases, dct):
# Itertate over ObservableField members and install descriptors
# this is wrong
for k,v in dict(dct).iteritems():
if v isinstance(ObservableField):
dct[k] = ObservableField._copy()
return super(DataObjectMeta, klass).__new__(klass, name, bases, dct)
# but maybe we should install event handlers here instead
# e.g. on_html_update?
class DataObject(object):
__metaclass__ = DataObjectMeta
def on_update(self, observable_field, immediate=False):
class MyDataObject(DataObject):
html = ObservableField()
json = ObservableField()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment