python中functools.wraps的作用

functools.wraps 的作用是将原函数对象的指定属性复制给包装函数对象, 默认有 modulenamedoc,或者通过参数选择。代码如下:

import logging.handlers
import time
import copy
import sys
import os
import logging
import functools


def create_logger():
    logfile = sys.path[0] + os.sep + 'notedb.log'
    handler = logging.handlers.RotatingFileHandler(logfile, mode='a')
    fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
    fmtstr = logging.Formatter(fmt)
    handler.setFormatter(fmtstr)
    logger = logging.getLogger('Message')
    logger.addHandler(handler)
    return logger


def logging_warpper(logger):
    def warpper_(func):
        @functools.wraps(func)
        def warpper(*args, **kwargs):
            try:
                print("begin the func %s" % (time.time()))
                print("The func address is %s " % (func.__name__))
                func(*args, **kwargs)
                print("end the func %s" % (time.time()))
            except:
                err = "There was an exception in  "
                err += func.__name__
                logger.exception(err)

                raise
        return warpper
    return warpper_


@logging_warpper(create_logger())
def addfunc(list_seq, args):
    seq = copy.deepcopy(list_seq)
    print(sum(x * x for x in seq))
    for key, value in args.items():
        print(key, value, end=' ')
    print('\n')


dict = {1: 'yangyc', 2: 'chen'}
list_use = list(range(10))
addfunc(list_use, dict)
print("The finally func name is :", addfunc.__name__)

输出结果:

begin the func 1508897893.4947305
The func address is addfunc 
285
1 yangyc 2 chen 

end the func 1508897893.4947305
The finally func name is : addfunc

func.name 为原函数addfunc的name

如果不添加functools.wraps修饰器,代码如下:

import logging.handlers
import time
import copy
import sys
import os
import logging
import functools


def create_logger():
    logfile = sys.path[0] + os.sep + 'notedb.log'
    handler = logging.handlers.RotatingFileHandler(logfile, mode='a')
    fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
    fmtstr = logging.Formatter(fmt)
    handler.setFormatter(fmtstr)
    logger = logging.getLogger('Message')
    logger.addHandler(handler)
    return logger


def logging_warpper(logger):
    def warpper_(func):
        def warpper(*args, **kwargs):
            try:
                print("begin the func %s" % (time.time()))
                print("The func address is %s " % (func.__name__))
                func(*args, **kwargs)
                print("end the func %s" % (time.time()))
            except:
                err = "There was an exception in  "
                err += func.__name__
                logger.exception(err)

                raise
        return warpper
    return warpper_


@logging_warpper(create_logger())
def addfunc(list_seq, args):
    seq = copy.deepcopy(list_seq)
    print(sum(x * x for x in seq))
    for key, value in args.items():
        print(key, value, end=' ')
    print('\n')


dict = {1: 'yangyc', 2: 'chen'}
list_use = list(range(10))
addfunc(list_use, dict)
print("The finally func name is :", addfunc.__name__)

输出结果如下:

begin the func 1508897997.7467523
The func address is addfunc 
285
1 yangyc 2 chen 

end the func 1508897997.7467523
The finally func name is : warpper

最终的func.name 为warpper

你可能感兴趣的:(python)