I created a class in R, and am trying to create a print function for that class. I'd like the print function to print the name of the object being passed to the print function. Using the standard deparse(substitute()) I can get the name of the variable, and this works when I call the print() function directly. But it doesn't work when I just run the variable from R Studio. It is obviously calling my print function. But there is some indirection that is causing it to lose the variable name. Here is an example:
# Define class 'myobj'
myobj <- function(val) {
obj <- structure(list(), class = c("myobj", "list"))
obj$value = val
return(obj)
}
# Write custom print function for 'myobj' class
#' @export
print.myobj <- function(x, ...) {
nm <- deparse1(substitute(x, env = environment()))
cat(paste0("My object name: ", nm, "\n"))
cat(paste0("My object value: ", x$value, "\n"))
invisible(x)
}
myInstance <- myobj(123)
# Prints name and value.
print(myInstance)
#> My object name: myInstance
#> My object value: 123
# Prints value, but name is local variable 'x'.
myInstance
#> My object name: x
#> My object value: 123
It seems like when you run the variable directly, it is getting nested in another frame or environment, such that the deparse(substitute()) isn't working.
How can I get my print function to print the name of the variable reliably, no matter how it is called?