Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/IPython/utils/strdispatch.py: 30%
33 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1"""String dispatch class to match regexps and dispatch commands.
2"""
4# Stdlib imports
5import re
7# Our own modules
8from IPython.core.hooks import CommandChainDispatcher
10# Code begins
11class StrDispatch(object):
12 """Dispatch (lookup) a set of strings / regexps for match.
14 Example:
16 >>> dis = StrDispatch()
17 >>> dis.add_s('hei',34, priority = 4)
18 >>> dis.add_s('hei',123, priority = 2)
19 >>> dis.add_re('h.i', 686)
20 >>> print(list(dis.flat_matches('hei')))
21 [123, 34, 686]
22 """
24 def __init__(self):
25 self.strs = {}
26 self.regexs = {}
28 def add_s(self, s, obj, priority= 0 ):
29 """ Adds a target 'string' for dispatching """
31 chain = self.strs.get(s, CommandChainDispatcher())
32 chain.add(obj,priority)
33 self.strs[s] = chain
35 def add_re(self, regex, obj, priority= 0 ):
36 """ Adds a target regexp for dispatching """
38 chain = self.regexs.get(regex, CommandChainDispatcher())
39 chain.add(obj,priority)
40 self.regexs[regex] = chain
42 def dispatch(self, key):
43 """ Get a seq of Commandchain objects that match key """
44 if key in self.strs:
45 yield self.strs[key]
47 for r, obj in self.regexs.items():
48 if re.match(r, key):
49 yield obj
50 else:
51 #print "nomatch",key # dbg
52 pass
54 def __repr__(self):
55 return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
57 def s_matches(self, key):
58 if key not in self.strs:
59 return
60 for el in self.strs[key]:
61 yield el[1]
63 def flat_matches(self, key):
64 """ Yield all 'value' targets, without priority """
65 for val in self.dispatch(key):
66 for el in val:
67 yield el[1] # only value, no priority
68 return