r - 如何每个 session 只显示一次警告?

标签 r lifecycle rlang

我的包中有一个功能应该谨慎使用。
用户应该意识到这一点,但如果他/她认为情况正常,那么每次调用该函数时都会显示警告。
我经常看到只显示一次的警告。它们调试起来非常痛苦,所以我找不到可重现的示例(如果有的话,我会添加一个)但它们显示特定的警告消息,然后是 rlang信息:

This warning is displayed once per session


有很多帮助想要调试这些消息(例如 hereherehere ,只需谷歌“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/

相关文章:

r - 在R中将字符串作为参数传递

r - 取消嵌套数据框列中的列表列表

r - 如何比较两个数据帧/表并在R中提取数据?

java - Vaadin 中布局(或组件)的生命周期?

android - 有必要拯救单例吗?

arrays - 数组中的维数和下标数不正确

r - Lyx 中的 knitr 安装

java - 在哪里配置 m2e 生命周期映射源目录和输出目录?

r - rlang 包中的 sym() 和 parse_expr() 有什么区别?