Created
April 28, 2010 18:17
-
-
Save robcowie/382486 to your computer and use it in GitHub Desktop.
Dict that supports wildcards in sequence keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import timeit | |
class Wildcard(object): | |
"""""" | |
@classmethod | |
def any(cls, *args, **kargs): | |
cmp_func = lambda other: True | |
return Wildcard(cmp_func, *args, **kargs) | |
@classmethod | |
def only_true(cls, *args, **kargs): | |
cmp_func = lambda other: other is True | |
return Wildcard(cmp_func, *args, **kargs) | |
@classmethod | |
def only_false(cls, *args, **kargs): | |
cmp_func = lambda other: other is False | |
return Wildcard(cmp_func, *args, **kargs) | |
def __init__(self, cmp_func, *args, **kargs): | |
self.cmp_func = cmp_func | |
def __cmp__(self, other): | |
return self.cmp_func(other) | |
class WildcardDict(dict): | |
"""""" | |
def _compare(self, existing, item): | |
"""""" | |
if len(existing) != len(item): | |
return False | |
m = (not isinstance(i, Wildcard) for i in item) | |
m2 = (not isinstance(i, Wildcard) for i in existing) | |
result = (cmp(a, b) for a, b, c, d in zip(existing, item, m, m2) if c and d) | |
return not [i for i in result if i] | |
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__': | |
s = """\ | |
mydict = WildcardDict({ | |
(1, 14, True): 'foo', | |
(10, 14, True): 'bar', | |
(11, 14, False): 'spaz', | |
(Wildcard.any(), 14, False): 'Donald Douche' | |
}) | |
mydict[ (1, 14, True) ] | |
mydict[ (Wildcard.any(), 14, False) ] | |
mydict[ (Wildcard.any(), 14, True) ] | |
(Wildcard.any(), 14, True) in mydict | |
(1, 14, Wildcard.only_true()) in mydict | |
'sod off' in mydict | |
mydict[ ('a', 14, False) ] | |
mydict[ ('b', 14, False) ] | |
mydict[ (1, 14, False) ] | |
mydict[ (Wildcard.any(), 14, False) ] | |
""" | |
t = timeit.Timer(s, "from __main__ import Wildcard, WildcardDict") | |
print "%.2f usec/pass" % (100000 * t.timeit(number=10000)/10000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one. Just ran it here http://python.codepad.org/JIJVgSX9