把好的代码记录下来 方便以后学习

 修改的函数参数装饰器

from functools import wraps
import time
import logging
def warn(timeout):
    #timeout=[timeout]  python 2.x
    def decorator(func):
        def wrapper(*args,**kargs):
            start = time.time()
            res = func(*args,**kargs)
            used = time.time()-start
            #if(used > timeout[0]):  python 2.x
            if(used > timeout):
                msg = '"%s":"%s" > %s' % (func.__name__,used,timeout)
                logging.warn(msg)
            return res
        def setTimeOut(k):
            nonlocal timeout
            timeout = k
            #timeout[0] = k    python 2.x
        wrapper.setTimeOut = setTimeOut
        return wrapper
    return decorator

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)
for _ in range(30):
    test()

 检测带参数类型的函数装饰器

from inspect import signature
def typeassert(*ty_args,**ty_kargs):
    def decorator(func):
        sig = signature(func)
        btypes = sig.bind_partial(*ty_args,**ty_kargs).arguments
        def wrapper(*args,**kargs):
            for name,obj in sig.bind_partial(*args,**kargs).arguments.items():
                if name  in btypes:
                    if not isinstance(obj,btypes[name]):
                        raise TypeError("%s must be %s" % (name,btypes))
            return func(*args,**kargs)
        return wrapper
    return decorator

@typeassert(int,str,list)
def f(a,b,c):
    print(a,b,c)

f(1,'abc',[1,2,3])
f(1,2,[1,2,3])

 

posted on 2018-11-22 22:14  nike_9527  阅读(199)  评论(0编辑  收藏  举报