美文网首页
python 参数可选的装饰器

python 参数可选的装饰器

作者: SkTj | 来源:发表于2019-12-04 11:06 被阅读0次

    from functools import wraps, partial
    import logging

    def logged(func=None, *, level=logging.DEBUG, name=None, message=None):
    if func is None:
    return partial(logged, level=level, name=name, message=message)

    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
    

    Example use

    @logged
    def add(x, y):
    return x + y

    @logged(level=logging.CRITICAL, name='example')
    def spam():
    print('Spam!')

    相关文章

      网友评论

          本文标题:python 参数可选的装饰器

          本文链接:https://www.haomeiwen.com/subject/kcdhpctx.html