##// END OF EJS Templates
Turn little test into proper doctest. Cleanup and document.
Fernando Perez -
Show More
@@ -1,65 +1,70 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 8 from IPython.hooks import CommandChainDispatcher
2 9 import IPython.hooks
3 10
4 import re
5 11
12 # Code begins
6 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 26 def __init__(self):
9 27 self.strs = {}
10 28 self.regexs = {}
29
11 30 def add_s(self, s, obj, priority= 0 ):
12 31 """ Adds a target 'string' for dispatching """
13 32
14 33 chain = self.strs.get(s, CommandChainDispatcher())
15 34 chain.add(obj,priority)
16 35 self.strs[s] = chain
17 36
18 37 def add_re(self, regex, obj, priority= 0 ):
19 38 """ Adds a target regexp for dispatching """
20 39
21 40 chain = self.regexs.get(regex, CommandChainDispatcher())
22 41 chain.add(obj,priority)
23 42 self.regexs[regex] = chain
24 43
25 44 def dispatch(self, key):
26 45 """ Get a seq of Commandchain objects that match key """
27 46 if key in self.strs:
28 47 yield self.strs[key]
29 48
30 49 for r, obj in self.regexs.items():
31 50 if re.match(r, key):
32 51 yield obj
33 52 else:
34 #print "nomatch",key
53 #print "nomatch",key # dbg
35 54 pass
36
37 55
38 56 def __repr__(self):
39 57 return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
40 58
41 59 def s_matches(self, key):
42 60 if key not in self.strs:
43 61 return
44 62 for el in self.strs[key]:
45 63 yield el[1]
46 64
47
48 65 def flat_matches(self, key):
49 66 """ Yield all 'value' targets, without priority """
50 67 for val in self.dispatch(key):
51 68 for el in val:
52 69 yield el[1] # only value, no priority
53 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