0

如何编写一个装饰器,将该函数的输入存储在 a 中list,并且只在存储后调用该函数n

4

3 回答 3

0

func每 100,000 次调用调用一次,在运行之前使用with @counter

def counter(func):
    def wrapper(val, *args, **kwargs):
        if val:
            wrapper.count = wrapper.count + 1
            if wrapper.count % 100000 == 0: # insert 100,000 at a time, should be speedier thanks to `.executemany()`
                to_logfile(str(wrapper.count) + '\n', 'counter2.log')
                return func(wrapper.valarr, *args, **kwargs)
            else:
                if len(wrapper.valarr)==1000000:
                    wrapper.vallarr = []
                wrapper.valarr.append([val])
                return
    wrapper.count = 0
    wrapper.valarr = []

    return wrapper

(随时提出改进建议)

于 2012-06-10T18:47:28.730 回答
0

这是一个类实现,因为其他人已经提交了函数实现:

class IntervalCache(object):

    def __init__(self, f):
        self._f = f
        self._cache = []
        self._n = 0
        self._interval = 1000

    def __call__(self, *args, **kwargs):
        if self._n == self._interval:
            result = [self.f(*c_args, **c_kwargs) for c_args, c_kwargs in self._cache]
            self._n = 0
            self._cache = []
            return result + [self.f(*args, **kwargs)]
        else:
            self._cache.append((*args, **kwargs))
            self._n += 1

    @property
    def getCache(self):
        return self._cache

    def resetCache(self):
        self._cache = []
        self._n = 0

    def getInterval(self):
        return self._interval

    def setInterval(self, value):
        self._interval = value

    interval = property(getInterval, setInterval)

用法:

#wrapping a function

@IntervalCache
def foo(*args, **kwargs):
    print args, kwargs
    return True

#setting the caching interval
foo.interval = 10

#calling foo a bunch of times
for i in range(20):
    print foo(i, i+1, bar=i*2)

#retrieving the contents of the cache
print foo.getCache()

#resetting the contents of the cache
foo.resetCache()
于 2012-06-10T19:34:29.367 回答
0

我假设

  • 您的函数接受任意数量的位置参数
  • f(a); f(b)是相同的f(a, b)
  • 它什么也不返回(任何结果都是副作用)

.

import functools

class Batcher(object):
    def __init__(self, n=100):
        self.n = n

    def __call__(self, fn):
        @functools.wraps(fn)
        def _fn(*args):
            _fn.cache.extend(args)
            _fn.calls += 1
            if _fn.calls == _fn.n:
                fn(*_fn.cache)
                _fn.cache = []
                _fn.calls = 0
        _fn.n = self.n
        _fn.cache = []
        _fn.calls = 0
        return _fn

然后测试它,

@Batcher(20)
def mysum(*args):
    print sum(args)

for i in range(1,25):
    mysum(i)

印刷

210    # <- result of sum(1..20)
于 2012-06-10T19:50:02.137 回答