【问题标题】:Conditionals decoration of functions in PythonPython中函数的条件修饰
【发布时间】:2014-10-27 17:37:17
【问题描述】:

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

  1. 如果 debug_mode == 0 不回显任何消息。
  2. 如果 debug_mode == 1 使用 print() 将消息回显到标准输出
  3. 如果 debug_mode == 2 将消息回显到日志文件中

我曾想过用函数装饰器(我以前从未使用过)来做到这一点。

实际上,我想替换一些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)

如果我没有传递参数 debug_mode 会更好,并且在装饰器函数中我可以直接从__main__ 使用调试状态。

【问题讨论】:

  • 为什么不将调试设置设为全局?
  • @bereal 如果找不到其他解决方案,那是我计划的解决方案。我曾经尽量避免使用全局变量。
  • 这里也一样,但是如果世界上有一个全局变量的位置,那么它就是调试和日志记录。你也可以依赖一个环境变量,如果不需要调试,debug 甚至可以返回原始函数。
  • 为什么不使用日志模块?打印调试信息很麻烦,任何诸如“何时刷新”之类的琐碎事情都可能会影响 print() 调用和效果出现之间的时间差。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2020-04-19
    • 2018-10-25
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2014-09-10
    相关资源
    最近更新 更多