[R-pkg-devel] .OnLoad v .OnAttach

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Sat Sep 23 11:50:39 CEST 2023


On 22/09/2023 8:35 p.m., Jonathan Godfrey wrote:
> Hello all,
> 
> An issue has been raised for my BrailleR package.   https://github.com/ajrgodfrey/BrailleR/issues/97#issuecomment-1732136521
> 
> I do make use of an .OnLoad() function for various tasks, including creation of a folder to put stuff in. The user gets to choose if this is temporary or fixed if the session is interactive. (all in zzz.R
> 
> What risks do I face if any of this .OnLoad() are moved to .OnAttach()?

If you move code from .onLoad() to .onAttach(), it won't be executed if 
the user never calls library(BrailleR) or require(BrailleR).  (This is a 
little simplified; there are other ways to attach a package, but they 
are rarely used.  More details on loading vs attaching below.)

If some setup is required by functions in your package even if they are 
called from other packages, it belongs in .onLoad(). A less convenient 
approach is for those functions to check whether the setup has happened 
every time you call them, and execute it if not.

Here are the details of the differences:

Loading makes the exported functions in the package available to other 
packages that import them, or call them using BrailleR::fn syntax.  The 
latter is also possible for users, and also triggers loading.  Once a 
package is loaded it normally stays loaded for the whole session, so 
.onLoad() will only be called once.

Attaching puts your package on the search list so that exported 
functions are available to the user without the prefix.  It will always 
be preceded by loading.  A user triggers attaching by making calls to 
library() or require().

If another package "Depends" on BrailleR, then loading that package will 
cause BrailleR to be attached.  The guidelines recommend against this, 
so most packages will use "Imports" instead.  That triggers loading but 
not attaching.

Duncan Murdoch



More information about the R-package-devel mailing list