相关疑难解决方法(0)

你会如何在python中编写一个@debuggable装饰器?

调试时,我喜欢打印出函数的所有输入和输出(我知道我需要一个更好的IDE,但是幽默我,这可以用于错误报告).所以,我最好喜欢:

@debuggable
def myfunc(argA,argB,argC):
    return argB+1
Run Code Online (Sandbox Code Playgroud)

并使用全局变量来打开或关闭调试.不,我猜你也不喜欢全局变量.

我能想到的最好的是:

DEBUG = True

def debuggable(func):
    if DEBUG:
        def decorated(*args):
            print "Entering ",func.func_name
            print "    args ",args
            ret = func(*args)
            print ret
            return ret
        return decorated
    else:
        return func

@debuggable
def myfunc(this,that):
    return this+that
Run Code Online (Sandbox Code Playgroud)

并运行:

>>> myfunc(1,3)
Entering  myfunc
   args  (1, 3)
4
Run Code Online (Sandbox Code Playgroud)

我怎样才能改善这一点?

python decorator

9
推荐指数
3
解决办法
4865
查看次数

标签 统计

decorator ×1

python ×1