如何访问正在跟踪的函数的返回值 [英] How to access a return value of a function that is being traced

查看:125
本文介绍了如何访问正在跟踪的函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法访问被指定为退出参数的函数跟踪的函数的返回值?这听起来很难理解,但是我无法简化问题而不会丢失信息。所以这里是一个简单的例子。



我们有一个简单的功能

  add10<  -  function(a){
a + 10
}

当调用add10退出时,我们想要调用一些函数。

  trace.exit()<  -  function() {
...
}

跟踪设置如下。

  trace(add10,exit = trace.exit)

我们打电话给add10

  add10(5)

据了解,现在, trace.exit 将在 add10 完成执行后调用。有没有办法在 trace.exit 中访问 add10 的返回值?



我觉得应该有。但是,使用 sys.frames 并查看环境,我无法得到它。



这样做的原因是希望捕获对某些功能的所有调用,并返回给他们的值。



UPD 使用包装器或类似东西的解决方案是很好的,但是 trace 已经实现了一个装饰器模式,所以我的问题是关于从 trace ,而不是解决R中装饰器的问题。

解决方案

不要使用一个显式地将返回值赋给一个局部变量的包装器:

  add10<  -  function(a){ 
a + 10
}

wrap< - function(f){function(...){..ret < - f(...)}}

add10_wrap< - wrap(add10)

trace.exit< - function(){
cat(sprintf(返回值:%s\\\
,sys.frame(-1)$ .. ret))
}

trace(add10_wrap,exit = trace.exit)

add10_wrap(5)

一个缺点是包装器总是返回invisi结果 - 这就是为什么上面的例子只打印格式化的输出。


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.

解决方案

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.

这篇关于如何访问正在跟踪的函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆