Skip to content
Prev 24405 / 63424 Next

S4 generic surprise

I discovered the following behavior when source'ing the same file
repeatedly as I edited it.  My generic stopped acting like a generic.  I
can't tell from the docs what, if any, behavior is expected in this
case.  R 2.4.0
[1] FALSE
Creating a new generic function for "foo" in ".GlobalEnv"
[1] "foo"
[1] 3
[1] 4
[1] TRUE
# The next step is where things start to go astray
[1] TRUE
[1] "foo"
[1] 2
# isGeneric is TRUE, but method lookup no longer works
# I think the cause is that the function foo that used
# to do the dispatch has been overwritten by my plain old
# function that returns 2.
[1] 2
[1] FALSE
Warning message:
generic function "foo" not found for removal in: removeGeneric("foo")
[1] TRUE

My mental model and R's diverged at the point I overwrote foo with a
regular function (foo <- function(object) 2).  At this point I thought R
would know that the function was no longer generic, and then would
rebuild the generic at the next setMethod.  Instead, R thought the
function remain generic, and so did not rebuild it at the next
setMethod.

If I had practiced the recommended style, I would have done
foo<-function(object) 2
setGeneric("foo")
and all would have been well.  So that's what I'll do.

I thought I'd report this in case others run into it, or somebody
considers this a matter that calls for documentation or R behavior
changes.