[ create a new paste ] login | about

Project: python
Link: http://python.codepad.org/JIJVgSX9    [ raw code | output | fork ]

Python, pasted on Apr 28:
# -*- coding: utf-8 -*-

class Wildcard(object):
    """"""
    def __init__(self, *args, **kargs):
        pass
        
    def __cmp__(self, other):
        return True



class WildcardDict(dict):
    """"""
    def _compare(self, existing, item):
        """"""
        if len(existing) != len(item):
            return False
        
        m = (not isinstance(i, Wildcard) for i in item)
        result = (cmp(a, b) for a, b, c in zip(existing, item, m) if c)
        return not filter(None, result)
        
    def __contains__(self, item):
        for key in super(WildcardDict, self).keys():
            if self._compare(key, item):
                return True
        return False
        
    def __getitem__(self, item):
        for key in super(WildcardDict, self).keys():
            if self._compare(key, item):
                return super(WildcardDict, self).__getitem__(key)
        raise KeyError(str(item))


if __name__ == '__main__':
    mydict = WildcardDict({
        (1, 14, True): 'foo',
        (10, 14, True): 'bar',
        (11, 14, False): 'spaz'
    })
    
    print mydict[ (1, 14, True) ]
    print mydict[ (Wildcard('*'), 14, False) ]
    print mydict[ (Wildcard('*'), 14, True) ]
    
    print (Wildcard('*'), 14, True) in mydict
    print 'sod off' in mydict
    
    mydict['ff']


Output:
1
2
3
4
5
6
7
8
9
10
11
foo
spaz
bar
True
False
Traceback (most recent call last):
  Line 51, in <module>
    mydict['ff']
  Line 34, in __getitem__
    raise KeyError(str(item))
KeyError: 'ff'


Create a new paste based on this one


Comments: