[Rd] trace() an S3-classed function in .GlobalEnv

Michael Chirico m|ch@e|ch|r|co4 @end|ng |rom gm@||@com
Tue Jun 7 08:09:29 CEST 2022


Consider:

foo <- function() {
  invisible(1 + 1)
}
trace(foo, quote(message("traced")), print=FALSE)
foo()
# traced

But with a minimal change:

class(foo) <- "bar"
trace(foo, quote(message("traced")), print=FALSE)
# Constructing traceable class “barWithTrace”
# Error in .classEnv(className) :
#   unable to find an environment containing class “bar”

I don't see anything like this mentioned in ?trace (nor does a Google
search turn up more than a handful of references to this error),
and from trying to debug what trace() is doing, we arrive to the error line[1]:

.makeTraceClass(traceClass, class(original))  #
methods:::.makeTraceClass("barWithTrace", "bar")

I don't quite follow what's going on here, but it looks like trace()
is trying to determine an S4 class definition for "bar", but isS4(bar)
is FALSE.

I can (apparently -- not sure if there are as yet-unseen downstream
consequences) work around the issue by unsetting the class, tracing,
then re-setting:

class(foo) <- NULL
trace(foo, quote(message("traced")), print=FALSE)
class(foo) <- "bar"

But obviously this is a bit clunky. Is this a bug, or am I missing something?

Mike C

[1] https://github.com/r-devel/r-svn/blob/e2a64a4e14adbc4e9e8635eaa8cbd2835ce1d764/src/library/methods/R/trace.R#L240



More information about the R-devel mailing list