web.web.utils.Memoize

Package web :: Package web :: Module utils :: Class Memoize |
[hide private]
[frames] | no frames]

# Class Memoize

source code

'Memoizes' a function, caching its return values for each input. If `expires` is specified, values are recalculated after `expires` seconds. If `background` is specified, values are recalculated in a separate thread.

    >>> calls = 0
    >>> def howmanytimeshaveibeencalled():
    ...     global calls
    ...     calls += 1
    ...     return calls
    >>> fastcalls = memoize(howmanytimeshaveibeencalled)
    >>> howmanytimeshaveibeencalled()
    1
    >>> howmanytimeshaveibeencalled()
    2
    >>> fastcalls()
    3
    >>> fastcalls()
    3
    >>> import time
    >>> fastcalls = memoize(howmanytimeshaveibeencalled, .1, background=False)
    >>> fastcalls()
    4
    >>> fastcalls()
    4
    >>> time.sleep(.2)
    >>> fastcalls()
    5
    >>> def slowfunc():
    ...     time.sleep(.1)
    ...     return howmanytimeshaveibeencalled()
    >>> fastcalls = memoize(slowfunc, .2, background=True)
    >>> fastcalls()
    6
    >>> timelimit(.05)(fastcalls)()
    6
    >>> time.sleep(.2)
    >>> timelimit(.05)(fastcalls)()
    6
    >>> timelimit(.05)(fastcalls)()
    6
    >>> time.sleep(.2)
    >>> timelimit(.05)(fastcalls)()
    7
    >>> fastcalls = memoize(slowfunc, None, background=True)
    >>> threading.Thread(target=fastcalls).start()
    >>> time.sleep(.01)
    >>> fastcalls()
    9

Instance Methods | [hide private]
__init__(self, func, expires=None, background=True) | source code
__call__(self, *args, **keywords) | source code