Python 3:检查另一个函数是否调用了函数

时间:2018-04-08 02:50:58

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

在python 3中,有没有办法检查另一个函数是否执行了特定的函数?我想让计算机做一些事情,如果一个函数被自己调用,而另一个函数调用它。这是一个例子:

def x():
    y()

def y():
    """Psuedocode --->""" 
    if function y was called by function x:
        print ("function y was called by another function")
    elif function y was not called by function x:
        print ("function y was called not called by another function")

Input ----> x()
Output ---> function y was called by another function

Input ---> y()
Output ---> function y was not called by another function

1 个答案:

答案 0 :(得分:2)

您可以使用名为“Inspect”的Python功能。它返回一个帧记录列表。每条记录中的第三个元素是调用者名称。请参阅此处的文档:https://docs.python.org/3/library/inspect.html

import inspect
def x():
    print inspect.stack()[1][3]

def y():
    x()