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



在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

您可以使用名为"检查"的Python功能。它返回帧记录的列表。每条记录中的第三个元素是调用方名称。在此处参考文档:https://docs.python.org/3/library/inspect.html

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

最新更新