Search code examples
rdevtools

R check if function in a package was called from the package fun or externally


How can I check from within the package (exported) function if the current function execution has been called by the function from that package or it was called by external package / from global env.

My current approach, developed by experimenting:

myfun <- function(){
    current_call = sys.call()
    parent_call = sys.call(sys.parent())
    if(identical(current_call,parent_call) || !identical(environmentName(parent.env(environment(match.fun(parent_call[[1L]])))),"imports:mypkg")){
        cat("called externally\n")
    }
}

Seems to not handle anonymous functions constructed in the other packages which dependent on my package.
Not particularly devtools related but package development related which devtools address well.

Edit:
To goal is to invoke an action (cat() in above example) in any cases except the calls from my other functions within the same package.


Solution

  • Borrowing from data.table:::cedta, I put these two functions in a package called test

    myfun <- function() {
      te <- topenv(parent.frame(1))
      if(isNamespace(te) && getNamespaceName(te) == "test") { # <-- "test" is the name of the package
        cat("called from my package\n")
      } else cat("Not called from my package\n")
    }
    
    tester <- function() {
      myfun()
    }
    

    After loading the test package, I get these results

    test:::myfun()
    #Not called from my package
    test:::tester()
    #called from my package