R6 icon indicating copy to clipboard operation
R6 copied to clipboard

'self' triggers 'no visible binding for global variable'

Open James-G-Hill opened this issue 3 years ago • 5 comments

When defining an R6 object within a package, running 'Check' will cause 'self' to trigger 'no visible binding for global variable' message.

One way to fix it is:

if(getRversion() >= "2.15.1")  utils::globalVariables(c("self"))

Is there any other solution more targeted to a specific function rather than defined globally?

James-G-Hill avatar May 18 '21 14:05 James-G-Hill

FWIW I don't think you need any workarounds if you define your methods "inline".

E.g. here is a simple example: https://github.com/r-lib/progress/blob/master/R/progress.R#L179

gaborcsardi avatar May 18 '21 14:05 gaborcsardi

Hey @gaborcsardi, thanks for coming back to this. I'm working with @James-G-Hill on this one.

Might have misunderstood 'inline', if the reprex below isnt inline please do correct me :) The major difference between this example and the progress bar one is that the below is within a function.

#' func
#' @param ... opts
#' @examples
#'\dontrun{
#' obj_gen(bar = "fubar")
#'}
#'
obj_gen <- function(...){

  obj <- R6::R6Class("my_class",
              public = list(
                foo = NULL,
                initialize = function(bar = NA){
                  self$foo <- bar
                },
                print = function(){
                  cat("Anyone for ",
                      self$foo,
                      "?",
                      sep = "")
                }
              )
  )
  obj$new(...)
}

The note and warning is only generated when self is called in a function, ie in print, but not in initialise.

B-Fernandez avatar May 18 '21 15:05 B-Fernandez

In this case you can put self <- NULL within the function as a workaround:

obj_gen <- function(...){
  self <- NULL
  obj <- R6::R6Class("my_class",
              public = list(
  ...

gaborcsardi avatar May 18 '21 15:05 gaborcsardi

That solves it. Its more explicit than: if(getRversion() >= "2.15.1") utils::globalVariables(c("self"))

Thanks,

B-Fernandez avatar May 18 '21 16:05 B-Fernandez

FYI - same issue for private, solved the same way:

obj_gen <- function(...){
  self <- NULL
  private <- NULL
  obj <- R6::R6Class("my_class",
              public = list(
  ...

gtm19 avatar Jun 16 '21 15:06 gtm19