[ create a new paste ] login | about

Link: http://codepad.org/2N6QMAWW    [ raw code | output | fork ]

Python, pasted on Jul 2:
import functools

def cached(f):
    _cache = {}
    @functools.wraps(f)
    def wrapper(self, *args, **kwargs):
        key = '-|-'.join(map(unicode, args))\
             +'-|-'.join('%s-:-%s' % x for x in kwargs.iteritems())
        if key in _cache:
            return _cache[key]
        ret = f(*args, **kwargs)
        _cache[key] = ret
        return ret
    return wrapper

class foo:
    @cached
    def bar(self):
        print "run!"
        return 1

if __name__ == "__main__":
    a, b = foo(), foo()
    print [a.bar() for i in range(3)]
    print [a.bar() for i in range(3)]


Output:
1
2
3
4
5
6
Traceback (most recent call last):
  Line 24, in <module>
    print [a.bar() for i in range(3)]
  Line 11, in wrapper
    ret = f(*args, **kwargs)
TypeError: bar() takes exactly 1 argument (0 given)


Create a new paste based on this one


Comments: