[R-pkg-devel] if statements in NAMESPACE file
Duncan Murdoch
murdoch@dunc@n @end|ng |rom gm@||@com
Wed Sep 29 20:45:40 CEST 2021
On 29/09/2021 2:13 p.m., Andrew Simmons wrote:
> I noticed in the Writing R Extensions manual, it says that within a
> NAMESPACE file, "Only very simple conditional processing of if statements
> is implemented.".
> I tried it out myself by importing a Windows exclusive function:
>
>
> if (.Platform$OS.type == "windows")
> importFrom(utils, getWindowsHandles)
>
>
> It also says in the manual that a NAMESPACE file "is not processed as R
> code", so I'm wondering if anyone knows exactly how if statements are
> handled within a NAMESPACE file.
For a question like this, going to the source is really the only choice.
NAMESPACE is parsed when the package is installed, using the function
parseNamespaceFile from the base package.
What that function does is to parse NAMESPACE as if it is R code, then
go through the unevaluate expressions. If it comes across one that is
an "if", it evaluates it in the global environment. But usually that's
not *your* global environment, that's the global environment that is in
place while the package is being installed.
If the condition is TRUE, it handles the clause that follows; if FALSE,
it will look at the "else" clause.
So your
if (.Platform$OS.type == "windows")
would be fine because .Platform is in the base package, so it's
guaranteed to be available. I suspect something like
if (stats::runif(1) > 0.5) export(someFunction)
would work too, for a particularly frustrating experience for your
users. It would mean half the installs export the function, and half don't.
Duncan Murdoch
More information about the R-package-devel
mailing list