strdispatch.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """String dispatch class to match regexps and dispatch commands.
  2. """
  3. # Stdlib imports
  4. import re
  5. # Our own modules
  6. from IPython.core.hooks import CommandChainDispatcher
  7. # Code begins
  8. class StrDispatch(object):
  9. """Dispatch (lookup) a set of strings / regexps for match.
  10. Example:
  11. >>> dis = StrDispatch()
  12. >>> dis.add_s('hei',34, priority = 4)
  13. >>> dis.add_s('hei',123, priority = 2)
  14. >>> dis.add_re('h.i', 686)
  15. >>> print(list(dis.flat_matches('hei')))
  16. [123, 34, 686]
  17. """
  18. def __init__(self):
  19. self.strs = {}
  20. self.regexs = {}
  21. def add_s(self, s, obj, priority= 0 ):
  22. """ Adds a target 'string' for dispatching """
  23. chain = self.strs.get(s, CommandChainDispatcher())
  24. chain.add(obj,priority)
  25. self.strs[s] = chain
  26. def add_re(self, regex, obj, priority= 0 ):
  27. """ Adds a target regexp for dispatching """
  28. chain = self.regexs.get(regex, CommandChainDispatcher())
  29. chain.add(obj,priority)
  30. self.regexs[regex] = chain
  31. def dispatch(self, key):
  32. """ Get a seq of Commandchain objects that match key """
  33. if key in self.strs:
  34. yield self.strs[key]
  35. for r, obj in self.regexs.items():
  36. if re.match(r, key):
  37. yield obj
  38. else:
  39. # print("nomatch",key) # dbg
  40. pass
  41. def __repr__(self):
  42. return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
  43. def s_matches(self, key):
  44. if key not in self.strs:
  45. return
  46. for el in self.strs[key]:
  47. yield el[1]
  48. def flat_matches(self, key):
  49. """ Yield all 'value' targets, without priority """
  50. for val in self.dispatch(key):
  51. for el in val:
  52. yield el[1] # only value, no priority
  53. return