~ellisonbg/ipython/bugfixes0411409

« back to all changes in this revision

Viewing changes to IPython/strdispatch.py

  • Committer: ville
  • Date: 2008-02-16 09:50:47 UTC
  • mto: (0.12.1 ipython_main)
  • mto: This revision was merged to the branch mainline in revision 990.
  • Revision ID: ville@ville-pc-20080216095047-500x6dluki1iz40o
initialization (no svn history)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from IPython.hooks import CommandChainDispatcher
 
2
import IPython.hooks
 
3
 
 
4
import re
 
5
 
 
6
class StrDispatch(object):
 
7
    """ Dispatch (lookup) a set of strings / regexps for match """
 
8
    def __init__(self):
 
9
        self.strs = {}
 
10
        self.regexs = {}
 
11
    def add_s(self, s, obj, priority= 0 ):
 
12
        """ Adds a target 'string' for dispatching """
 
13
        
 
14
        chain = self.strs.get(s, CommandChainDispatcher())
 
15
        chain.add(obj,priority)
 
16
        self.strs[s] = chain
 
17
 
 
18
    def add_re(self, regex, obj, priority= 0 ):
 
19
        """ Adds a target regexp for dispatching """
 
20
        
 
21
        chain = self.regexs.get(regex, CommandChainDispatcher())
 
22
        chain.add(obj,priority)
 
23
        self.regexs[regex] = chain
 
24
 
 
25
    def dispatch(self, key):
 
26
        """ Get a seq of Commandchain objects that match key """
 
27
        if key in self.strs:
 
28
            yield self.strs[key]
 
29
        
 
30
        for r, obj in self.regexs.items():
 
31
            if re.match(r, key):
 
32
                yield obj
 
33
            else: 
 
34
                #print "nomatch",key
 
35
                pass
 
36
            
 
37
 
 
38
    def __repr__(self):
 
39
        return "<Strdispatch %s, %s>" % (self.strs, self.regexs)
 
40
    
 
41
    def s_matches(self, key):
 
42
        if key not in self.strs:
 
43
             return
 
44
        for el in self.strs[key]:
 
45
            yield el[1]
 
46
        
 
47
        
 
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
 
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()    
 
 
b'\\ No newline at end of file'