[Rd] isNamespaceLoaded() while the namespace is loading

Gábor Csárdi c@@rd|@g@bor @end|ng |rom gm@||@com
Fri Jan 21 17:26:23 CET 2022


We ran into a bug in our package that seems to boil down to
isNamespaceLoaded() returning TRUE for namespaces that R is currently
loading.

We had something like this in an .onLoad function:

if (isNamespaceLoaded("upstream")) {
  upstream::upstream_function()
}

Which seems OK, unless upstream (recursively) imports the package
having this code. Should that happen, the loading of upstream triggers
the loading of this package as well and isNamespaceLoaded() seems to
return TRUE, even though the namespace of upstream is not fully loaded
yet, and we get an error that looks like this:

Error : .onLoad failed in loadNamespace() for 'foo', details:
     call: NULL
     error: 'upstream_function' is not an exported object from
'namespace:upstream'

I wonder if isNamespaceLoaded() returning TRUE is correct in this
case, or returning FALSE would be better. Or maybe it would make sense
to have a way to query the packages that are being loaded currently?

AFAICT this works, but it does use some implementation details from
loadNamespace(), so it does not seem like a proper solution:

dynGet("__NameSpacesLoading__", NULL)

Another workaround is something like this:

  is_loaded <- function(pkg) {
    if (!isNamespaceLoaded(pkg)) return(FALSE)
    tryCatch({
      loadNamespace(pkg)
      TRUE
    }, error = function(err) FALSE)
  }

which forces an error for currently loading namespaces by triggering a
(fake) recursive dependency.

Thanks,
Gabor



More information about the R-devel mailing list