问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/24687062/how-to-access-a-return-value-of-a-function-that-is-being-traced