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

Jignesh Sutar jsutar at gmail.com
Fri Mar 7 11:58:48 CET 2014


Hi All, thanks for the comments and yes I am a tad confused and a little
out of my comfort zone with what I am trying to achieve here. Is this below
any better way (or even worse?) of trying to achieve this. Though this
doesn't actually achieve what I want it to, it may nonetheless highlight
the concept in principle?

def funcA(runfromB=False):
    if runfromB is False:"running from funcA" # print only if running from
funcA
    print "running from funcA or funcB" #print when running from either
function
    if runfromB is True: "running from funcB" # print only when running
from funcB

def funcB(runfromB):
    funcA(runfromB=runfromB)

funcB(runfromB=True)


On 6 March 2014 20:37, Jerry Hill <malaclypse2 at gmail.com> wrote:

> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140307/d38254c3/attachment.html>


More information about the Tutor mailing list