Is there any way of accessing return value of a function that is being traced by a function specified as exit param to trace? That sounds hard to understand, but I was not able to simplify the question without loosing the information. So here is a simple example.
We have a simple function
add10 <- function(a){
a + 10
}
And some function that we want to be called when call to add10 exits.
trace.exit() <- function(){
...
}
Tracing is set up the following way.
trace(add10, exit=trace.exit)
And we do a call to add10
add10(5)
As I understand of right now, trace.exit
will be called after add10
finished executing. Is there any way to access return value of add10
inside trace.exit
?
I feel that there should be. But playing with sys.frames
and looking through environments I was not able to get it.
The reason for doing so is a wish to capture all calls to some function and return values they give.
UPD Solution with wrapper or something similar is nice, but trace
already implements a decorator pattern, so my question is about accessing return value from trace
, not about solving the problem of decorators in R.
There are 2 places where we can see the method return value: In the Debugger Immediate window, using the $ReturnValue keyword. To open the Immediate window while debugging, choose Debug -> Windows -> Immediate (or press keyboard shortcut: Ctrl + Alt + I). In the Debugger Autos window.
Where is it stored? Well, it isn't stored. It actually gets erased from memory. When we call a function, the function executes its code and after the return, that particular function call gets wiped out from working memory ( the browser is in charge of the cleanup task).
What happens when you call a function (which has return value) without assigning it to anything? -->The function will be executed, either make no sense like your case or make a lot of senses like modifying a static variable or a global variable. The return value will be ignored.
Why don't you use a wrapper that explicitly assigns the return value to a local variable:
add10 <- function(a){
a + 10
}
wrap <- function(f) { function(...) { ..ret <- f(...) } }
add10_wrap <- wrap(add10)
trace.exit <- function() {
cat(sprintf("Return value: %s\n", sys.frame(-1)$..ret))
}
trace(add10_wrap, exit=trace.exit)
add10_wrap(5)
One downside is that the wrapper will always return invisible results -- that's why the above example only prints the formatted output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With