[Rd] Time to drop globalenv() from searches in package code?

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Thu Sep 15 21:33:48 CEST 2022


The author of this Stackoverflow question 
https://stackoverflow.com/q/73722496/2554330 got confused because a typo 
in his code didn't trigger an error in normal circumstances, but it did 
when he ran his code in pkgdown.

The typo was to use "x" in a test, when the local variable was named 
".x".  There was no "x" defined locally or in the package or its 
imports, so the search got all the way to the global environment and 
found one.  (The very confusing part for this user was that it found the 
right variable.)

This author had suppressed the "R CMD check" check for use of global 
variables.  Obviously he shouldn't have done that, but he's working with 
tidyverse NSE, and that causes so many false positives that it is 
somewhat understandable he would suppress one too many.

The pkgdown simulation of code in examples doesn't do perfect mimicry of 
running it at top level; the fake global environment never makes it onto 
the search list.  Some might call this a bug, but I'd call it the right 
search strategy.

My suggestion is that the search for variables in package code should 
never get to globalenv().  The chain of environments should stop after 
handling the imports.  (Probably base package functions should also be 
implicitly imported, but nothing else.)

I suspect this change would reveal errors in lots of packages, but the 
number of legitimate uses of the current search strategy has got to be 
pretty small nowadays, since we've been getting warnings for years about 
implicit imports from other standard packages.

Duncan Murdoch



More information about the R-devel mailing list