您将如何在python中编写@debuggable装饰器? [英] How would you write a @debuggable decorator in python?

查看:84
本文介绍了您将如何在python中编写@debuggable装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试时,我喜欢打印出函数的所有输入和输出(我知道我需要一个更好的IDE,但幽默的是,这可以用于错误报告)。因此,我理想上希望拥有:

  @debuggable 
def myfunc(argA,argB,argC):
返回argB + 1

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



我能想到的最好的方法是:

  DEBUG =真

可调试(func):
如果已调试:
def装饰(* args):
打印 Entering,func.func_name
打印 args,args
ret = func(* args)
打印ret
return ret
返回修饰的
else:
return func

@debuggable
def myfunc(this,that):
返回this + that

并运行:

 >>> ; myfunc(1,3)
输入myfunc
args(1、3)
4

我该如何改善呢?

解决方案

使用调试器。说真的装饰要跟踪的每个函数都是一个坏主意。



Python

(来源: winpdb.org


When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:

@debuggable
def myfunc(argA,argB,argC):
    return argB+1

and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.

The best I can come up with is:

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

And running:

>>> myfunc(1,3)
Entering  myfunc
   args  (1, 3)
4

How can I improve that?

解决方案

Use a debugger. Seriously. Decorating every function you want to keep track is a bad idea.

Python has a debugger included, so you don't need a good IDE.

If you don't want to use a debugger, you can use the trace function.

import sys

@sys.settrace
def trace_debug(frame, event, arg):
    if event == 'call':
        print ("calling %r on line %d, vars: %r" % 
                (frame.f_code.co_name, 
                 frame.f_lineno,
                 frame.f_locals))
        return trace_debug
    elif event == "return":
        print "returning", arg

def fun1(a, b):
    return a + b

print fun1(1, 2)

That prints:

calling 'fun1' on line 14, vars: {'a': 1, 'b': 2}
returning 3
3

Even easier would be to use Winpdb:

It is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.

Features:

  • GPL license. Winpdb is Free Software.
  • Compatible with CPython 2.3 or later.
  • Compatible with wxPython 2.6 or later.
  • Platform independent, and tested on Ubuntu Gutsy and Windows XP.
  • User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.


(source: winpdb.org)

这篇关于您将如何在python中编写@debuggable装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆