When to use .onLoad vs .onAttach ?

I have historically in my packages set various options and auto-authentication via .onAttach and .onLoad but am not clear which is best to use.

For example googlesheets uses .onLoad to set options which I have taken my cue from but I wonder for options that are meant to be set by the user its better to set them .onAttach, with .onLoad saved only for non-user set options?

As I understand it now, .onAttach is called when a user types library(your_package) but I'm not so clear when .onLoad is called.

Are there any rules of thumb for when to use one other another?

Usually you want .onLoad, which—as the name suggests—runs when the package is loaded. If something has to happen before anything is run, that's the way to go. onAttach only runs when the library is attached, e.g. when somebody calls library(your_package). onLoad will also run when somebody loads but doesn't attach your package by calling your_package::your_function.

Reading:

http://r-pkgs.had.co.nz/r.html#r-differences

http://r-pkgs.had.co.nz/namespace.html#namespace

and the official docs at ?ns-hooks, if you haven't already read that.

3 Likes

.onAttach is only for interactive use, for example startup messages and so forth

You can call a function from a package without attaching the package with ::. For example you can use purrr::map without calling library(purrr) first (as you should usually do if you develop packages).The first time you call a function in that manner, the package is automatically loaded and .onLoad() is called (but not .onAttach())

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.