[Tutor] How to determine which function code is being called from

Jerry Hill malaclypse2 at gmail.com
Thu Mar 6 21:37:00 CET 2014


On Thu, Mar 6, 2014 at 12:00 PM, Jignesh Sutar <jsutar at gmail.com> wrote:
> Hi I'm trying to exclude a certain line of code if the function is called by
> another function, see illustration below:

As other have said, this is not often a good idea.  That said, it is
possible to inspect the call stack to see what called a particular
function, like this (python 3.3):

iimport inspect

def funcA():
    caller = inspect.stack()[1][3]
    print('funcA was called by ' + caller)
    if caller == '<module>':
        print("running from funcA")# print only if running from funcA
    if caller in ('<module>', 'funcB'):
        print("running from funcA or funcB") # print when running from
either function
    if caller == 'funcB':
        print("running from funcB") # print only when running from funcB

def funcB():
    funcA()

print('----- Calling funcA() directly -----')
funcA()
print('----- Calling funcB() -----')
funcB()

Output:

>>>
----- Calling funcA() directly -----
funcA was called by <module>
running from funcA
running from funcA or funcB
----- Calling funcB() -----
funcA was called by funcB
running from funcA or funcB
running from funcB
>>>


-- 
Jerry


More information about the Tutor mailing list