Global variable in a package - which approach is more recommended?

I understand that, in general, global variables are evil, and I should avoid them, but if my package really has a global variable, which of these two approaches is better? And are there any other recommended approaches?

  • Using the environment visible to the package

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

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

I know that there are other topics that ask how to achieve global variables, but I have not seen a discussion on which it is recommended

+1
source share
2 answers

Some packages use hidden variables (variables starting with .), for example .Random.seed, .Last.valuethey do in the R base. 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() .

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

. .

+3

, "" , , (.GlobalEnv, GlobalEnv as.environment(1)) , , .

- . , () . , , :

myFunction <- local({

    cache <- list() # or numeric(0) or whatever

    function(x,y,z){ 

        # calculate the index of the answer 
        # (most of the time this is a trivial calculation, often the identity function)
        indx = answerIndex(x,y,z)

        # check if the answer is stored in the cache
        if(indx %in% names(cacheList))
            # if so, return the answer
            return(cacheList[indx])

        [otherwise, do lots of calculations or data queries]

        # store the answer
        cahceList[indx] <<- answer

        return(answer)
    }

})

local , <<-, , , ( ) local() myFunction.

+3

Source: https://habr.com/ru/post/1694316/


All Articles