【问题标题】:R: Storing function symbols for later reuse and making a global "undebug()"R:存储函数符号以供以后重用并制作全局“ undebug()”
【发布时间】:2016-12-28 20:25:38
【问题描述】:

我想为debug() 函数编写一个包装器,以便在需要时删除所有调试标志。

对于搜索路径中的函数,它很简单。

.debugged <- NULL
debug.wrapper <- function(fun){
    f <- deparse(substitute(fun))
    .debugged <<- unique(c(.debugged, f))
    debug(f)    
}
debug.wrapper.off <- function() {
    z=sapply(.debugged, undebug)
    .debugged <<- NULL    
}

之所以有效,是因为我可以使用函数符号的字符版本。

f <-  function() print("hello")
debug.wrapper(f)
isdebugged(f)
# [1] TRUE
debug.wrapper.off()
isdebugged(f)
# [1] FALSE

无论如何使用命名空间它都不起作用:

debug.wrapper(tools:::psnice)
# Error in debug(f) could not find function "tools:::psnice"

还有:

debug(substitute(tools:::psnice))
# Error in debug(fun, text, condition) : argument must be a function

如何存储函数符号以供以后重复使用?

【问题讨论】:

  • 试试match.fun,两者都接受。将行 f &lt;- deparse(substitute(fun)) 更改为 f &lt;- match.fun(fun) 似乎可以解决问题。
  • @RichScriven:谢谢,我以不同的方式成功了,因为我意识到连接函数符号不涉及制作函数副本。

标签: r debugging symbols


【解决方案1】:

注意

似乎连接函数符号会创建一种“软指针”而不是副本,即:

x <- c(tools:::psnice, identity)

取第一个函数,我们得到:

x[[1]]    
# function (pid = Sys.getpid(), value = NA_integer_) 
# {
#     res <- .Call(ps_priority, pid, value)
#     if (is.na(value)) 
#         res
#     else invisible(res)
# }
# <bytecode: 0x00000000189f1f80>
# <environment: namespace:tools>

字节码和环境与tools:::psnice相同。
因此un/debug(x[[1]]) 就像un/debug(tools:::psnice)

解决方案

鉴于上述说明,解决方案是微不足道的。调试包装器定义为:

.debugged <- NULL
debug.wrapper <- function(fun){    
    .debugged <<- unique(c(.debugged, fun))
    debug(fun)    
}
debug.wrapper.off <- function() {
    z=sapply(.debugged, undebug)
    .debugged <<- NULL    
}

使用它们会带来:

f <-  function() print("hello")
debug.wrapper(f)
debug.wrapper(tools:::psnice)
isdebugged(f)
# [1] TRUE
isdebugged(tools:::psnice)
# [1] TRUE
debug.wrapper.off()
isdebugged(f)
isdebugged(tools:::psnice)
.debugged
# NULL

当然,当传递fun 是一个字符串时,可以添加条件来管理大小写。

感谢@Rich Scriven,他提供了有用的见解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多