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

Martin Maechler m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Wed Jun 8 12:44:21 CEST 2022


>>>>> Michael Chirico 
>>>>>     on Mon, 6 Jun 2022 23:09:29 -0700 writes:

    > 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?

Just a short note of  semi-confirmation:

At the time S4 generics and methods were introduced into R,
trace() was made much more flexible, notably to be able to trace
S4 methods.

It can well be that it originally also worked for functions with
an explicit S3 class, but as such functions are very rare, it
could well be you've found a bug, namely that trace() assumes
that if a function has a non-trivial class, it must be an S4
one.

... and I know you know how to report bugs ;-)

Thank you in advance!
Martin

    > Mike C

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

    > ______________________________________________
    > R-devel using r-project.org mailing list
    > https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list