wahani / modules

Modules in R

Home Page:https://cran.r-project.org/package=modules

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Does re-use-ing a module require an explicit `detach`?

barryrowlingson opened this issue · comments

If I use a module file with attach=TRUE, then changes in the module file don't get reflected if I re-run use. Example:

No foo function:

> foo(3)
Error in foo(3) : could not find function "foo"

This file defines one function:

> system("cat mod.Rmod")
foo <- function(x) {
    sqrt(x)
}

Use it and try it:

> use("mod.Rmod",attach=TRUE)
> foo(3)
[1] 1.732051

Now edit the file to return x squared, use it again and get an update message:

> system("cat mod.Rmod")
foo <- function(x) {
    x*x
}
> use("mod.Rmod",attach=TRUE)
Replacing attached import/use on search path for: modules:mod.Rmod.

but foo still does square-root:

> foo(3)
[1] 1.732051

detach and re-use and I get the new behaviour:

> detach(2)
> foo
Error: object 'foo' not found
> use("mod.Rmod",attach=TRUE)
> foo(3)
[1] 9
> 

Is this expected or documented? Using reInit=TRUE doesn't change the above either.

I'm currently using R 3.6.3 and modules: 0.8.0

Thanks

@barryrowlingson thanks for bringing this up.

This is a bit surprising indeed. I think it has something to do with the mechanism to prevent having multiple copies of the same module on the search path. I guess as long as it is the same name, it is not attached, and any changes are ignored. Although the console output suggests something else. I will check how this is implemented at the moment.

One question: Do you expect the module you reattach to be at the same, or first position on the search path?

I think re-attached at the same position would be best, since that would mean the same set of potential masked objects would apply.

@barryrowlingson you can test the fix after installing the PR with

remotes::install_github("wahani/modules", "bugfix/reattach-module")

The new behavior will be equivalent to do an explicit detach before calling use again. After that procedure the reattached module will be at the first position on the search path.

This was a special situation when working in the global environment and is now inline with the behavior inside of a module. Actually we tried to detach the module, but it works a bit different for .GlobalEnv. The only sane way I found was to use detach. It is also somewhat inline with how package loading with library and the whole attaching / detaching mechanism works in general.