[Rd] S4 generic surprise

Ross Boylan ross at biostat.ucsf.edu
Thu Mar 29 23:27:22 CEST 2007

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

> foo <- function(object) 3
> isGeneric("foo")
> setMethod("foo", "matrix", function(object) 4)
Creating a new generic function for "foo" in ".GlobalEnv"
[1] "foo"
> foo(0)
[1] 3
> foo(matrix(0))
[1] 4
> isGeneric("foo")
[1] TRUE
# The next step is where things start to go astray
> foo <- function(object) 2
> isGeneric("foo")
[1] TRUE
> setMethod("foo", "matrix", function(object) 40)
[1] "foo"
> foo(0)
[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.
> foo(matrix(0))
[1] 2
> removeGeneric("foo")
Warning message:
generic function "foo" not found for removal in: removeGeneric("foo") 
> isGeneric("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

If I had practiced the recommended style, I would have done
foo<-function(object) 2
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
Ross Boylan                                      wk:  (415) 514-8146
185 Berry St #5700                               ross at biostat.ucsf.edu
Dept of Epidemiology and Biostatistics           fax: (415) 514-8150
University of California, San Francisco
San Francisco, CA 94107-1739                     hm:  (415) 550-1062

More information about the R-devel mailing list