0

I'm trying to initialize and store some package specific information when a package is first loaded and have found a lot of good information on ways to do this in How to store some package specific information in R and How to run some code on load of package. However, one function I want to call during package loading verifies the inheritance relationships of several classes defined in the package, but this returns different results from what I would have expected. I can come up with different ways to work around this problem but I'm trying to understand what I'm doing wrong and was hoping someone could explain it to me.

A minimal example of the package source code to reproduce the problem follows.

# package reference classes
setClass("myclass", representation(value = "numeric"), 
                    prototype = prototype(value = 42))
setClass("myderivedclass", contains = "myclass")

# package on load function
.onLoad <- function(lib, pkg){  
    if (!extends("myderivedclass", "myclass")) {
        warning("something's not right")
    }
}

Now during package .onLoad, extends("myderivedclass", "myclass") evaluates to FALSE (triggering the warning), but of course once the package is loaded it evaluates to TRUE, which is what I would have expected. Initializing objects with either class during .onLoad works just fine so it's not that the class definitions aren't loaded yet.

Thank you very much for any help on how I should be doing this kind of test during .onLoad or what I might have misunderstood about inheritance here.

Session info:

> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
Community
  • 1
  • 1
sebkopf
  • 2,335
  • 19
  • 18
  • 1
    I _think_ you want to use `setLoadAction`, for the reasons outlined on it's help page and in the comments by John Chambers in [this thread](http://r.789695.n4.nabble.com/check-warning-with-onLoad-and-setClass-td4677489.html) – Martin Morgan Apr 26 '14 at 02:34
  • Thank you, using ```setLoadAction``` does solve the problem! I've also experimented some more and found using ```.onAttach``` instead of ```.onLoad``` works as well. Do you know what is the recommended approach? (```.onAttach``` vs. ```setLoadAction``` ?) – sebkopf Apr 26 '14 at 04:58
  • Since Chambers (a creator of the S language, and of the S4 and reference class system) says to use setLoadAction, I'd take that as the recommendation! – Martin Morgan Apr 26 '14 at 05:31
  • good point, advice well taken, thanks again – sebkopf Apr 26 '14 at 05:40

1 Answers1

0

For the sake of completeness, this is how it worked with setLoadAction instead of .onLoad

setLoadActions(function(ns) {
    if (!extends("myderivedclass", "myclass")) {
        warning("something's not right")
    } else {
        message("everything all right")
    }
}) 

In this way, extends("myderivedclass", "myclass")properly evaluates to TRUE during package loading.

sebkopf
  • 2,335
  • 19
  • 18