root/galaxy-central/eggs/bx_python-0.5.0_dev_f74aec067563-py2.6-macosx-10.6-universal-ucs2.egg/bx/cookbook/__init__.py

リビジョン 3, 2.8 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

行番号 
1"""
2Various useful utilities, mostly taken from the ASPN Python cookbook.
3"""
4
5seq_types = type( () ), type( [] )
6
7def 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
16def 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
34import types
35
36def cachedmethod(function):
37    return types.MethodType(Memoize(function), None)
38
39
40class 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
57class 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
80class 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()))
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。