Skip to content

Instantly share code, notes, and snippets.

@vwood
Created October 27, 2010 11:30
Show Gist options
  • Save vwood/648874 to your computer and use it in GitHub Desktop.
Save vwood/648874 to your computer and use it in GitHub Desktop.
Simple Reactive programming.
from types import FunctionType
class cell:
def __init__(self, *args):
self.i_depend_on = []
self.depends_on_me = []
self.set(*args)
def get(self):
return self.value
def add(self, depends):
self.depends_on_me.append(depends)
def remove(self, depends):
self.depends_on_me.remove(depends)
def set(self, *args):
for depend in self.i_depend_on:
depend.remove(self)
if (len(args) == 0 or
(len(args) > 1 and not isinstance(args[0], FunctionType))):
raise TypeError("A Cell must have a value, OR a function and cell args.")
if type(args[0]) == FunctionType:
self.__class__ = cell_formula
self.calculation = args[0]
self.i_depend_on = list(args[1:])
self.calc()
for depend in self.i_depend_on:
depend.add(self)
else:
self.__class__ = cell_value
self.value = args[0]
self.calculation = None
for depends in self.depends_on_me:
depends.calc()
class cell_value(cell):
def calc(self): pass
class cell_formula(cell):
def calc(self):
self.value = self.calculation(*[depends.value for depends in self.i_depend_on])
for depends in self.depends_on_me:
depends.calc()
@vwood
Copy link
Author

vwood commented May 5, 2012

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