python 9-4 如何实现属性可修改的函数装饰器,python3 nolocal或者在python2中列表方式

9-4 如何实现属性可修改的函数装饰器

解决方案:
python3 nolocal
为包裹函数添加一个函数,用来修改闭包中使用的自由变量.
python中,使用nonlocal访问嵌套作用域中的变量引用,或者在python2中列表方式,这样就不会在函数本地新建一个局部变量

from functools import wraps
import time
import logging
def warn(timeout):
    timeout = [timeout]
    def deco(func):
        def wrapper(*args,**kwargs):
            start = time.time()
            res = func(*args,**kwargs)
            used = time.time() -start
            if used > timeout[0]:
                msg = '"%s" : %s > %s'%(func.__name__,used,timeout[0])
                logging.warn(msg)
            return res
        def setTimeout(k):
            #nonlocal timeout
            timeout[0] = k
        print "timeout was given...."
        wrapper.setTimeout = setTimeout
        return wrapper
    return deco

from random import randint

@warn(1.5)
def test():
    print "in test..."
    while randint(0,1):
        time.sleep(0.5)

for _ in range(30):
    test()

test.setTimeout(1)

print "after set to 1...."

for _ in range(30):
    test()

你可能感兴趣的:(python实战)