1 | """ |
---|
2 | Various useful utilities, mostly taken from the ASPN Python cookbook. |
---|
3 | """ |
---|
4 | |
---|
5 | seq_types = type( () ), type( [] ) |
---|
6 | |
---|
7 | def flatten( *args ): |
---|
8 | for arg in args: |
---|
9 | if type( arg ) in seq_types: |
---|
10 | for elem in arg: |
---|
11 | for f in flatten( elem ): |
---|
12 | yield f |
---|
13 | else: |
---|
14 | yield arg |
---|
15 | |
---|
16 | def cross_lists(*sets): |
---|
17 | """Return the cross product of the arguments""" |
---|
18 | wheels = map(iter, sets) |
---|
19 | digits = [it.next() for it in wheels] |
---|
20 | while True: |
---|
21 | yield digits[:] |
---|
22 | for i in range(len(digits)-1, -1, -1): |
---|
23 | try: |
---|
24 | digits[i] = wheels[i].next() |
---|
25 | break |
---|
26 | except StopIteration: |
---|
27 | wheels[i] = iter(sets[i]) |
---|
28 | digits[i] = wheels[i].next() |
---|
29 | else: |
---|
30 | break |
---|
31 | |
---|
32 | # Cached / memoized methods |
---|
33 | |
---|
34 | import types |
---|
35 | |
---|
36 | def cachedmethod(function): |
---|
37 | return types.MethodType(Memoize(function), None) |
---|
38 | |
---|
39 | |
---|
40 | class Memoize: |
---|
41 | def __init__(self,function): |
---|
42 | self._cache = {} |
---|
43 | self._callable = function |
---|
44 | |
---|
45 | def __call__(self, *args, **kwds): |
---|
46 | cache = self._cache |
---|
47 | key = self._getKey(*args,**kwds) |
---|
48 | try: return cache[key] |
---|
49 | except KeyError: |
---|
50 | cachedValue = cache[key] = self._callable(*args,**kwds) |
---|
51 | return cachedValue |
---|
52 | |
---|
53 | def _getKey(self,*args,**kwds): |
---|
54 | return kwds and (args, ImmutableDict(kwds)) or args |
---|
55 | |
---|
56 | |
---|
57 | class memoized(object): |
---|
58 | """Decorator that caches a function's return value each time it is called. |
---|
59 | If called later with the same arguments, the cached value is returned, and |
---|
60 | not re-evaluated. |
---|
61 | """ |
---|
62 | def __init__(self, func): |
---|
63 | self.func = func |
---|
64 | self.cache = {} |
---|
65 | def __call__(self, *args): |
---|
66 | try: |
---|
67 | return self.cache[args] |
---|
68 | except KeyError: |
---|
69 | self.cache[args] = value = self.func(*args) |
---|
70 | return value |
---|
71 | except TypeError: |
---|
72 | # uncachable -- for instance, passing a list as an argument. |
---|
73 | # Better to not cache than to blow up entirely. |
---|
74 | return self.func(*args) |
---|
75 | def __repr__(self): |
---|
76 | """Return the function's docstring.""" |
---|
77 | return self.func.__doc__ |
---|
78 | |
---|
79 | |
---|
80 | class ImmutableDict(dict): |
---|
81 | '''A hashable dict.''' |
---|
82 | |
---|
83 | def __init__(self,*args,**kwds): |
---|
84 | dict.__init__(self,*args,**kwds) |
---|
85 | def __setitem__(self,key,value): |
---|
86 | raise NotImplementedError, "dict is immutable" |
---|
87 | def __delitem__(self,key): |
---|
88 | raise NotImplementedError, "dict is immutable" |
---|
89 | def clear(self): |
---|
90 | raise NotImplementedError, "dict is immutable" |
---|
91 | def setdefault(self,k,default=None): |
---|
92 | raise NotImplementedError, "dict is immutable" |
---|
93 | def popitem(self): |
---|
94 | raise NotImplementedError, "dict is immutable" |
---|
95 | def update(self,other): |
---|
96 | raise NotImplementedError, "dict is immutable" |
---|
97 | def __hash__(self): |
---|
98 | return hash(tuple(self.iteritems())) |
---|