Skip to content

Commit c161fbb

Browse files
committed
add NotifyList class
1 parent 047820d commit c161fbb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

geomdl/_collections.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# callback handlers for list modification
2+
# https://stackoverflow.com/a/13259435/1162349
3+
4+
import sys
5+
6+
_pyversion = sys.version_info[0]
7+
8+
def callback_method(func):
9+
def notify(self,*args,**kwargs):
10+
for _,callback in self._callbacks:
11+
callback()
12+
return func(self,*args,**kwargs)
13+
return notify
14+
15+
class NotifyList(list):
16+
extend = callback_method(list.extend)
17+
append = callback_method(list.append)
18+
remove = callback_method(list.remove)
19+
pop = callback_method(list.pop)
20+
__delitem__ = callback_method(list.__delitem__)
21+
__setitem__ = callback_method(list.__setitem__)
22+
__iadd__ = callback_method(list.__iadd__)
23+
__imul__ = callback_method(list.__imul__)
24+
25+
#Take care to return a new NotifyList if we slice it.
26+
if _pyversion < 3:
27+
__setslice__ = callback_method(list.__setslice__)
28+
__delslice__ = callback_method(list.__delslice__)
29+
def __getslice__(self,*args):
30+
return self.__class__(list.__getslice__(self,*args))
31+
32+
def __getitem__(self,item):
33+
if isinstance(item,slice):
34+
return self.__class__(list.__getitem__(self,item))
35+
else:
36+
return list.__getitem__(self,item)
37+
38+
def __init__(self,*args):
39+
list.__init__(self,*args)
40+
self._callbacks = []
41+
self._callback_cntr = 0
42+
43+
def register_callback(self,cb):
44+
self._callbacks.append((self._callback_cntr,cb))
45+
self._callback_cntr += 1
46+
return self._callback_cntr - 1
47+
48+
def unregister_callback(self,cbid):
49+
for idx,(i,cb) in enumerate(self._callbacks):
50+
if i == cbid:
51+
self._callbacks.pop(idx)
52+
return cb
53+
else:
54+
return None
55+

0 commit comments

Comments
 (0)