##// END OF EJS Templates
Turn little test into proper doctest. Cleanup and document.
Fernando Perez -
Show More
@@ -1,13 +1,32 b''
1 """String dispatch class to match regexps and dispatch commands.
2 """
3
4 # Stdlib imports
5 import re
6
7 # Our own modules
1 from IPython.hooks import CommandChainDispatcher
8 from IPython.hooks import CommandChainDispatcher
2 import IPython.hooks
9 import IPython.hooks
3
10
4 import re
5
11
12 # Code begins
6 class StrDispatch(object):
13 class StrDispatch(object):
7 """ Dispatch (lookup) a set of strings / regexps for match """
14 """Dispatch (lookup) a set of strings / regexps for match.
15
16 Example:
17
18 >>> dis = StrDispatch()
19 >>> dis.add_s('hei',34, priority = 4)
20 >>> dis.add_s('hei',123, priority = 2)
21 >>> dis.add_re('h.i', 686)
22 >>> print list(dis.flat_matches('hei'))
23 [123, 34, 686]
24 """
25
8 def __init__(self):
26 def __init__(self):
9 self.strs = {}
27 self.strs = {}
10 self.regexs = {}
28 self.regexs = {}
29
11 def add_s(self, s, obj, priority= 0 ):
30 def add_s(self, s, obj, priority= 0 ):
12 """ Adds a target 'string' for dispatching """
31 """ Adds a target 'string' for dispatching """
13
32
@@ -31,9 +50,8 b' class StrDispatch(object):'
31 if re.match(r, key):
50 if re.match(r, key):
32 yield obj
51 yield obj
33 else:
52 else:
34 #print "nomatch",key
53 #print "nomatch",key # dbg
35 pass
54 pass
36
37
55
38 def __repr__(self):
56 def __repr__(self):
39 return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
57 return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
@@ -44,22 +62,9 b' class StrDispatch(object):'
44 for el in self.strs[key]:
62 for el in self.strs[key]:
45 yield el[1]
63 yield el[1]
46
64
47
48 def flat_matches(self, key):
65 def flat_matches(self, key):
49 """ Yield all 'value' targets, without priority """
66 """ Yield all 'value' targets, without priority """
50 for val in self.dispatch(key):
67 for val in self.dispatch(key):
51 for el in val:
68 for el in val:
52 yield el[1] # only value, no priority
69 yield el[1] # only value, no priority
53 return
70 return
54
55
56 def test():
57 d = StrDispatch()
58 d.add_s('hei',34, priority = 4)
59 d.add_s('hei',123, priority = 2)
60 print list(d.dispatch('hei'))
61 d.add_re('h.i', 686)
62 print list(d.flat_matches('hei'))
63
64 if __name__ == '__main__':
65 test() No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now