我的包中有一个功能应该谨慎使用。
用户应该意识到这一点,但如果他/她认为情况正常,那么每次调用该函数时都会显示警告。
我经常看到只显示一次的警告。它们调试起来非常痛苦,所以我找不到可重现的示例(如果有的话,我会添加一个)但它们显示特定的警告消息,然后是 rlang
信息:
This warning is displayed once per session
有很多帮助想要调试这些消息(例如 here 、 here 或 here ,只需谷歌“r 这个警告每个 session 显示一次”)
我认为包裹
lifecyle
经常将它们用于软弃用,但我无法在 lifecycle:::lifecycle_build_message
中发现诀窍.我怎样才能在我的包裹中抛出这样的警告?
编辑:
这是一个可重现的示例。您必须重新启动 R session 才能再次显示它。如您所见,
options(warn=2)
没有影响。options(warn=2)
xx=c("Sepal.Width")
tidyselect::vars_select(names(iris), xx)
最佳答案
在tidyselect::vars_select
的情况下,诀窍在 tidyselect:::inform_once
.
if (env_has(inform_env, id)) {
return(invisible(NULL))
}
inform_env[[id]] <- TRUE
# ....
inform(paste_line(
msg, silver("This message is displayed once per session.")
))
环境
inform_env
维护记录是否已显示给定消息。在
lifecycle
的情况下,它与环境类似 deprecation_env
用于 deprecate_warn
deprecate_warn <- function(....) {
msg <- lifecycle_build_message(when, what, with, details, "deprecate_warn")
# ....
if (verbosity == "quiet") {
return(invisible(NULL))
}
if (verbosity == "default" && !needs_warning(id) && ....) {
return(invisible(NULL))
}
# ....
if (verbosity == "default") {
# Prevent warning from being displayed again
env_poke(deprecation_env, id, Sys.time());
msg <- paste_line(
msg,
silver("This warning is displayed once every 8 hours."),
silver("Call `lifecycle::last_warnings()` to see where this warning was generated.")
)
}
# ....
}
needs_warning <- function(id) {
last <- deprecation_env[[id]]
if (is_null(last)) {
return(TRUE)
}
# ....
# Warn every 8 hours
(Sys.time() - last) > (8 * 60 * 60)
}
关于r - 如何每个 session 只显示一次警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61075780/