From hb at biostat.ucsf.edu  Mon Oct 14 00:30:19 2013
From: hb at biostat.ucsf.edu (Henrik Bengtsson)
Date: Sun, 13 Oct 2013 15:30:19 -0700
Subject: [Rd] reg.finalizer(): Is it safe for the finalizer function to
 attach/load a package?
Message-ID: <CAFDcVCRx4GoGEm3ybGCAGhMou3VVbQqRB2Kyuu6veXGGwiFrxA@mail.gmail.com>

>From the help/docs it is pretty clear that one could/should only
assume that the 'base' namespace is available when a finalizer
function is evaluated. What is not clear to me is whether you can
safely attach/load packages in your finalizer function. For example,
are the following finalizer functions safe?

reg.finalizer(e, function(e, ...) {
  library("tcltk")
  .Tcl("close $con")
})

and

reg.finalizer(e, function(e, ...) {
  tcltk::.Tcl("close $con")
})

What about non-core packages, e.g.

reg.finalizer(e, function(e, ...) {
  library("R.oo")
  finalize(e)
})

(here finalize() is a generic function, but it's just an example)?.
I'm worried that (re-)attaching packages in a finalizer could be
competing with R's terminating sequence of detaching/unloading
packages.  The reason why I believe this, is that 'R CMD check' on
some of my packages occasionally generate:

* checking for unstated dependencies in R code ... WARNING
Error in attachNamespace(ns, pos = pos, dataPath = dataPath, deps) :
  namespace is already attached
Warning in function (env)  :
  Object may not be finalize():d properly because the R.oo package
failed to reload: Package: 0x0000000006a2f1b8
See the information on DESCRIPTION files in the chapter 'Creating R
packages' of the 'Writing R Extensions' manual.

Knowing whether it is considered safe/unsafe to (re-)attach a package
in the finalizer will help me troubleshoot the above and decide on an
alternative design for my finalizers.

Any help/feedback is appreciated.

/Henrik



[Rd] reg.finalizer(): Is it safe for the finalizer function to attach/load a package?
Henrik Bengtsson