powerline/powerline/lib/memoize.py
ZyX 06211cbe63 Unify imports
Now imports follow the following structure:

1. __future__ line: exactly one line allowed:

        from __future__ import (unicode_literals, division, absolute_import, print_function)

   (powerline.shell is the only exception due to problems with argparse).
2. Standard python library imports in a form `import X`.
3. Standard python library imports in a form `from X import Y`.
4. and 5. 2. and 3. for third-party (non-python and non-powerline imports).
6. 3. for powerline non-test imports.
7. and 8. 2. and 3. for powerline testing module imports.

Each list entry is separated by exactly one newline from another import. If
there is module docstring it goes between `# vim:` comment and `__future__`
import. So the structure containing all items is the following:

    #!/usr/bin/env python
    # vim:fileencoding=utf-8:noet

    '''Powerline super module'''

    import sys

    from argparse import ArgumentParser

    import psutil

    from colormath.color_diff import delta_e_cie2000

    from powerline.lib.unicode import u

    import tests.vim as vim_module

    from tests import TestCase

.
2014-09-01 00:25:24 +04:00

43 lines
1.2 KiB
Python

# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from functools import wraps
from powerline.lib.monotonic import monotonic
def default_cache_key(**kwargs):
return frozenset(kwargs.items())
class memoize(object):
'''Memoization decorator with timeout.'''
def __init__(self, timeout, cache_key=default_cache_key, cache_reg_func=None):
self.timeout = timeout
self.cache_key = cache_key
self.cache = {}
self.cache_reg_func = cache_reg_func
def __call__(self, func):
@wraps(func)
def decorated_function(**kwargs):
if self.cache_reg_func:
self.cache_reg_func(self.cache)
self.cache_reg_func = None
key = self.cache_key(**kwargs)
try:
cached = self.cache.get(key, None)
except TypeError:
return func(**kwargs)
# Handle case when time() appears to be less then cached['time'] due
# to clock updates. Not applicable for monotonic clock, but this
# case is currently rare.
if cached is None or not (cached['time'] < monotonic() < cached['time'] + self.timeout):
cached = self.cache[key] = {
'result': func(**kwargs),
'time': monotonic(),
}
return cached['result']
return decorated_function