python笔记_查看函数调用栈的一个小技巧

一、背景

最近在看一个开源框架的源码,涉及到的内容非常杂乱,有的函数不知道是在什么时候被谁给调用了?调用的时候传入了什么参数?为了解决这个问题,写了一个小的装饰器。

二、实现

这个装饰器函数主要参考了logging模块中的findCaller,源码如下:

def findcaller(func):
    def wrapper(*args,**kwargs):
        import sys
        f=sys._getframe()
        filename=f.f_back.f_code.co_filename
        lineno=f.f_back.f_lineno
        print '######################################'
        print 'caller filename is ',filename
        print 'caller lineno is',lineno
        print 'the passed args is',args,kwargs
        print '######################################'
        func(*args,**kwargs)
    return wrapper

只要加上这个装饰器,就能在调用函数前看到这个函数被哪个文件中的第几行调用,并且传入的参数是什么。例子如下:

#caller.py
from class_A import A
a1=A()
a2=A(1)
a3=A(2)
a2.func(3)

#class_A.py
class A(object):
    def __init__(self,num=0):
        print num
    @findcaller
    def func(self,num=None):
        print num

#执行caller,得到结果如下:
######################################
caller filename is  caller.py
caller lineno is 5
the passed args is (, 3) {}
######################################

可以看到是caller.py中的第5行a2.func(3)调用到了func函数,传入参数是3.

你可能感兴趣的:(python笔记_查看函数调用栈的一个小技巧)