在函数上添加装饰器
你想使用额外的代码包装一个函数,可以定义一个装饰器函数。
import time
from functools import wraps
import logging
def timethis_and_log(func):
"""
Decorator that reports the execution time"""
@wraps(func)
def wrapper(*args,**kwargs):
start=time.time()
result=func(*args,**kwargs)
end=time.time()
print(func.__name__,end-start)
logging.warning('fuction is running {}'.format(func.__name__))
return result
return wrapper
@timethis_and_log
def countdown(n):
while n >0:
n -=1
countdown(100000)
记录了运行时间,以及log信息
创建装饰器时保留函数元信息
任何时候你定义装饰器的时候,都应该使用 functools 库中的 @wraps 装饰器来注解底层包装函数,这个装饰器使这个函数的重要的元信息比如名字、文档字符串、注解和参数签名都不丢失了。
#定义一个带参数的装饰器
写一个装饰器,给函数添加日志功能,同时允许用户指定日志的级别跟其他选项
from functools import wraps
import logging
def logged(level,name=None,message=None):
"""
add logging to a function level is the logging level ,name
is the logger name,and message is the log message.if name and message aren't speccified
they default to the function's module and name"""
def decorate(func):
logname=name if name else func.__module__
log=logging.getLogger(logname)
logmsg =message if message else func.__name__
@wraps(func)
def wrapper(*args,**kwargs):
log.log(level,logmsg )
return func(*args,**kwargs)
return wrapper
return decorate
@logged(logging.CRITICAL)
def add(x,y):
return x+y
a=add(3,2)
@logged(logging.CRITICAL, 'example')
def spam():
pass
b=spam()
运行结果如下