This repository was archived by the owner on Oct 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvartree.py
102 lines (77 loc) · 2.69 KB
/
vartree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# Copyright 2010 Robert Spanton
# This file is part of compd.
#
# compd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# compd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Foobar. If not, see <http://www.gnu.org/licenses/>.
"A tree of subscribable variables"
class SVar:
"A subscribable variable"
def __init__(self):
self.subscribers = []
self.value = None
def set(self, val):
self.value = val
self._emit()
def get(self):
return self.value
def subscribe(self, fn, args):
self.subscribers.append( (fn, args) )
def unsubscribe(self, fn):
self.subscribers = [ x for x in self.subscribers if x[0] != fn ]
def _emit(self):
for sub in self.subscribers:
sub[0]( self.value, *sub[1] )
class VarTree:
real_attrs = ["_vars", "_name"]
def __init__(self, name = "Unknown"):
self._vars = {}
self._name = name
def __setattr__(self, name, value):
if name in self.__dict__ or name in VarTree.real_attrs:
self.__dict__[name] = value
return
_vars = self.__dict__["_vars"]
if isinstance( value, VarTree ):
value._name = "%s.%s" % (self._name, name)
_vars[name] = value
else:
if name not in _vars:
_vars[name] = SVar()
_vars[name].set(value)
def __getattr__(self, name):
if name in self._vars:
val = self._vars[name]
if isinstance( val, VarTree ):
return val
return val.get()
raise AttributeError
def __delattr__(self, name):
self._vars.popitem(name)
def subscribe(root, name, fn, args = []):
s = name.split(".")
cur = root
assert s[0] == "sr"
s = s[1:]
while len(s) > 0:
cur = cur._vars[s[0]]
s = s[1:]
if not isinstance(cur, SVar):
raise AttributeError
cur.subscribe( fn, args )
def unsubscribe(root, fn):
# Traverse all nodes in the tree, unsubscribing things
for x in root._vars.items():
if isinstance(x, VarTree):
VarTree.unsubscribe( x, fn )
elif isinstance(x, SVar):
x.unsubscribe(fn)