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

Alan Gauld alan.gauld at freenet.co.uk
Thu Mar 2 12:25:38 CET 2006


Ben,

> I want myfunction in the pseudocode below return something 
> different if it was called from indexfunction.

There are several approaches to this.

> def indexfunction():   blah
>
> def myfunction():
>    if <myfunction was called from indexfunction>:  return x
>    else:   return <header> + x + <footer>

The simplest approach simply includes a "sender" parameter in 
myfunction and callers supply a link or label to indicate who is 
calling. This is the approach adopted by many GUI toolkits.
It works best if you want to identify an object rather than a 
function however since the caller simply passes self as the value.

The other possibility is to use the traceback module and 
examine the call stack. Thats a moderately advanced technique 
and you may want to google for some examples of using tracebacks.

HTH,

Alan G.


More information about the Tutor mailing list