[Rd] Can a function know what other function called it?

Robert Gentleman rgentlem at fhcrc.org
Sat May 23 22:55:09 CEST 2009

Hi Kynn,

Kynn Jones wrote:
> Suppose function foo calls function bar.  Is there any way in which
> bar can find out the name of the function that called it, "foo"?

 essentially yes. You can find out about the call stack by using sys.calls and
sys.parents etc. The man page plus additional manuals should be sufficient, but
let us know if there are things that are not clear.

> There are two generalization to this question that interest me.
> First, can this query go farther up the call stack?  I.e. if bar now
> calls baz, can baz find out the name of the function that called the
> function that called it, i.e. "foo"?  Second, what other information,

 yes - you can (at least currently) get access to the entire calling stack and
some manipulations can be performed.

> beside its name, can bar find about the environment where it was
> called?  E.g. can it find out the file name and line number of the

 there is no real concept of file and line number associated with a function
definition (nor need their even be a name - functions can be anonymous).

 If you want to map back to source files then I think that currently we do not
keep quite enough information when a function is sourced. Others may be able to
elaborate more (or correct my mistakes).  I think we currently store the actual
text for the body of the function so that it can be used for printing, but we
don't store a file name/location/line number or anything of that sort. It could
probably be added, but would be a lot of work, so it would need someone who
really wanted it to do that.

 However, you can find out lots of other things if you want.  Do note that while
 it is possible to determine which function initiated the call, it is not
necessarily possible to figure out which of the calls (if there is more than one
in the body of the function) is active.  R does not keep track of things in that
way. To be clear if foo looks like:

  foo <- function(x) {
    x = sqrt(x)
  and you have a breakpoint in bar, you could not (easily) distinguish which of
the two calls to bar was active. There is no line counter or anything of that
sort available.

 best wishes

> function call?
> Thanks!
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

Robert Gentleman, PhD
Program in Computational Biology
Division of Public Health Sciences
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N, M1-B514
PO Box 19024
Seattle, Washington 98109-1024
rgentlem at fhcrc.org

More information about the R-devel mailing list