Python中函数的条件装饰

时间:2014-09-03 09:19:08

标签: python python-3.x python-decorators

出于调试目的,我想编写一个函数来执行此操作:

  1. 如果debug_mode == 0不回显任何消息。
  2. 如果debug_mode == 1使用print()
  3. 将消息回显到stdout
  4. 如果debug_mode == 2将消息回显给日志文件
  5. 我认为用函数装饰器(我以前从未使用过)来做到这一点。

    实际上,我想用一些print()代替我在某些点上给我看中间值,同时学习函数装饰器。

    我不想创建一个类来做到这一点。这是我的方法,但它不起作用:

    import logging
    
    FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s'
    logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')
    
    def debug(func):
        def _debug(deb=0, *args, **kwargs):
            if deb == 1:
                print(msg)
                func(*args, **kwargs)
            if deb == 2:
                logging.debug(msg)
        return _debug
    
    @debug
    def echo(msg, deb=0):
        pass
    
    if __name__ == "__main__":
        debug_mode = 1
        echo("This is a debugging message!", debug_mode)
    

    如果我不传递param debug_mode并且在装饰器函数中,我可以直接使用__main__中的调试状态。

1 个答案:

答案 0 :(得分:1)

代码的问题在于传递参数的方式。执行echo("This is a debugging message!", debug_mode)时,您实际上正在调用def _debug(deb=0, *args, **kwargs),并且所有参数都混乱(deb变为"This is a debugging message!"等)。在StackOverflow上,如何使用装饰器有一个惊人的tutorial

我不确定为什么你的代码需要*args, **kwargs。我个人认为在您的特定情况下不需要任何装饰。无论如何,出于教育目的,带有装饰器的工作代码可能就像:

import logging

FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s'
logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')

def debug(func):
    def _debug(msg, deb=0):
        if deb == 1:
            func(msg, deb)
        if deb == 2:
            print 'Log: ' + msg + ' Level: ' + str(deb)
            logging.debug(msg)
    return _debug

@debug
def echo(msg, deb):
    print 'Echo: ' + msg + ' Level: ' + str(deb) 

if __name__ == "__main__":
    echo("This is a debugging message!")
    echo("This is a debugging message!", 0)
    echo("This is a debugging message!", 1)
    echo("This is a debugging message!", 2)

输出:

Echo: This is a debugging message! Level: 1
Log: This is a debugging message! Level: 2