0

In python 3, is there a way to check if another function executed a particular function? I want the computer to do something if a function was called by the itself and something else if another function called it. Here is an example:

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 Answer 1

3

You can use the Python feature called "Inspect". It returns a list of frame records. The third element in each record is the caller name. Refer docs here: https://docs.python.org/3/library/inspect.html

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

def y():
    x()
Sign up to request clarification or add additional context in comments.

3 Comments

Be aware that this method is fairly unreliable for production environments since it depends on the implementation of the underlying CPython.
Thank you so much for this answer. really helped.
Glad that I could help you :) .