包中的全局变量-更推荐使用哪种方法? [英] Global variable in a package - which approach is more recommended?

查看:63
本文介绍了包中的全局变量-更推荐使用哪种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实知道一般来说全局变量是邪恶的,我应该避免使用它们,但是如果我的程序包确实需要一个全局变量,那么这两种方法中哪个更好?还有其他建议的方法吗?

I do understand that generally global variables are evil and I should avoid them, but if my package does need to have a global variable, which of these two approaches are better? And are there any other recommended approaches?

  1. 使用程序包可见的环境

  1. Using an environment visible to the package

pkgEnv <- new.env()  
pkgEnv$sessionId <- "xyz123"

  • 使用options

    options("pkgEnv.sessionId" = "xyz123")
    

  • 我知道还有其他一些线程在询问如何实现全局变量,但是我还没有看到关于推荐哪个变量的讨论

    I know there are some other threads that ask about how to achieve global variables, but I haven't seen a discussion on which one is recommended

    推荐答案

    某些包使用隐藏变量(以.开头的变量),例如.Random.seed.Last.value在基R中执行.可以做到

    Some packages use hidden variables (variables that begin with a .), like .Random.seed and .Last.value do in base R. In your package you could do

    e <- new.env()
    assign(".sessionId", "xyz123", envir = e)
    ls(e)
    # character(0)
    ls(e, all = TRUE)
    # [1] ".sessionId"
    

    但是在您的包裹中,您无需分配e.您可以使用.onLoad()挂钩在加载程序包时分配变量.

    But in your package you don't need to assign e. You can use a .onLoad() hook to assign the variable upon loading the package.

    .onLoad <- function(libname, pkgname) {
        assign(".sessionId", "xyz123", envir = parent.env(environment()))
    }
    

    请参见此问题及其答案,以获取有关软件包变量的一些很好的解释

    See this question and its answers for some good explanation on package variables.

    这篇关于包中的全局变量-更推荐使用哪种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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