[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

We had something like this in an .onLoad function:

if (isNamespaceLoaded("upstream")) {

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

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)
    }, error = function(err) FALSE)

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


More information about the R-devel mailing list