Format: text/x-python
⬇ Download File (1.8 KB)
   1  """String dispatch class to match regexps and dispatch commands.
   2  """
   3  
   4  # Stdlib imports
   5  import re
   6  
   7  # Our own modules
   8  from IPython.core.hooks import CommandChainDispatcher
   9  
  10  # Code begins
  11  class StrDispatch(object):
  12      """Dispatch (lookup) a set of strings / regexps for match.
  13  
  14      Example:
  15  
  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      """
  23  
  24      def __init__(self):
  25          self.strs = {}
  26          self.regexs = {}
  27  
  28      def add_s(self, s, obj, priority= 0 ):
  29          """ Adds a target 'string' for dispatching """
  30  
  31          chain = self.strs.get(s, CommandChainDispatcher())
  32          chain.add(obj,priority)
  33          self.strs[s] = chain
  34  
  35      def add_re(self, regex, obj, priority= 0 ):
  36          """ Adds a target regexp for dispatching """
  37  
  38          chain = self.regexs.get(regex, CommandChainDispatcher())
  39          chain.add(obj,priority)
  40          self.regexs[regex] = chain
  41  
  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]
  46  
  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
  53  
  54      def __repr__(self):
  55          return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
  56  
  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]
  62  
  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
  69