Tuesday, May 6, 2014

Cool decorators for python

这里是一些日常看到用到的多快好省decorators,积累起来当做自己的笔记。这些decorators可能已经被广泛流传了很长时间了,所以很难找到第一个出处。所以在此谢谢各位前辈分享。

timer

用来profile一个函数用了多长时间运行:

def timer(func):
    '''
    To time a function.
    ''' 
    def wrapper(*arg):
        t = time.time()
        res = func(*arg)
        print func.func_name, str("%.4f" % (time.time() - t)) + " second"
        return res

    return wrapper

在运行的时候,将输入的参数全部输出出来,方便debug:

def print_arg(function):
    def wrapper(*args, *kwargs):
        print "Argument:", args, kwargs
        return function(*args, *kwargs)
    return wrapper

获取当前运行的函数的名字

sys._getframe().f_code.co_name

这个其实不是decorator,因为事实上没法做decorator。假设我为了方便将这个函数搞成了一lambda表达式:

get_name = lambda : sys._getframe().f_code.co_name

在一个我要debug的函数里面调用了这个表达式:

print get_name()    #<lambda>

但如果正常使用的话:

def my_debug_function(*args):
    print sys._getframe().f_code.co_name

# OUTPUT:
my_debug_function

所以为了偷懒我就写了这个一个snippet for sublimetext:

<snippet>
    <content><![CDATA[
    func_name = sys._getframe().f_code.co_name
        ${1:print func_name}
        ${2:logging.debug(func_name)}
    ]]></content>
    <tabTrigger>get_name</tabTrigger>
    <scope>source.python</scope>
</snippet>

Written with StackEdit.

No comments:

Post a Comment