[Tutor] How can a function know where it was called from

Kent Johnson kent37 at tds.net
Thu Mar 2 14:20:12 CET 2006

Noufal Ibrahim wrote:
> On Thu, March 2, 2006 3:55 pm, Ben Vinger wrote:
>>I want myfunction in the pseudocode below return something different if it
>>was called from indexfunction.
> I'm new to this but maybe it would be good if you passed the appropriate
> "version" of "myfunction" to indexfunction from where the original
> decision of which one to use was made rather than doing it at the lower
> levels.
> Something like.
> def myfunwithheaders(x):
>   return header + x + footer
> def myfunwithoutheaders(x):
>   return x
> def main():
>    blah
>    if needheaders:
>     myfunction(myfunwithheaders)
>    else:
>     myfunction(myfunwithoutheaders)
> def myfunction(ret):
>    x = "whatever"
>    return ret(x)
> I'd appreciate if some of the more experienced folks on the list comment
> on the general approach.

This seems needlessly complicated in this case. I would just give 
myfunction() a default parameter:

def myfunction(includeHeader=False):
    x = 'whatever'
    if not includeHeader:
       return x
       return <header> + x + <footer>

Alternately you could have two versions of myfunction, one that includes 
the header/footer and one that does not. The one that does include the 
header could call the other one to generate 'x', if that is complex.

I would only consider inspecting the stack in an extreme situation, 
maybe if I was modifying myfunction but had no control over the calling 
code. But this solution smells badly - it is complex, fragile (will 
break if the name of the calling function changes) and obscure (there is 
no clue at the point of call that the behaviour is going to be different).

Anyway if you must, take a look at this recipe:


More information about the Tutor mailing list