Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Proof of concept protection against free variables. The purpose is to avoid passing a function to a subprocess for parallel evaluation when that function depends on variables that are only available in the parent process.
getNonPackageVars <- function (pos=-1L, envir=as.environment(pos)) {
npvarnames <- c()
while (TRUE) {
if (identical(envir, emptyenv()) ||
identical(envir, .BaseNamespaceEnv)) {
## If we hit the empty env, then we started in a package
## namespace, so there are no non-package vars.
if (identical(envir, baseenv()))
message("Looking in env: ", capture.output(print(envir)))
npvarnames <- c(npvarnames, ls(envir=envir))
if (identical(envir, globalenv())) {
## After we process the global env, we're done
envir <- parent.env(envir)
getNonPackageFreeVars <- function (fun) {
npvars <- getNonPackageVars(environment(fun))
fun.freevars <- findGlobals(fun)
intersect(fun.freevars, npvars)
} <- function(what, ...) {
what <-
badvars <- getNonPackageFreeVars(what)
if (length(badvars) > 0) {
stop("Function contains free variables: ", deparse(badvars))
}, ...)
x <- 5
okfunc <- function (a, b) a + b
freevarfunc <- function (a) a + x + y
getNonPackageFreeVars(rnorm), list(a=1, b=2)), list(a=1)), list(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment