restrict_fn_env: Restrict function environment

View source: R/funky.R

restrict_fn_envR Documentation

Restrict function environment

Description

Build a new function with an optimal scope. Normally the entire environment tree (including the entire ancestry) is kept in memory as long as a function is present. This is a common cause for memory leaks. With restrict_fn_env() you create a function that has only the needed variables (copies) in the scope and the optimal scope ancestry can be defined by argument parent_env. Be sure, to choose the right environment for parent_env!

Usage

restrict_fn_env(
  fn,
  vars = NULL,
  lookup_env = environment(fn),
  parent_env = .GlobalEnv
)

Arguments

fn

A function whose parent scope should be restricted to the set of variables given in vars and the loaded packages.

vars

An optional object, telling which variables should be available in fn(). It can either be

  • a character vector holding the names of the variables which should looked up in the environment lookup_env.

  • a named list: In this case, the values are not looked up in lookup_env, but directly taken from the list item values and the list item names are used as variable names.

lookup_env

The environment holding the variables for which the names are defined in the character vector vars. If vars is a list or NULL, then lookup_env is not used. The default for lookup_env is the environment where the function fn was defined.

parent_env

The parent environment, which should be assigned to the restricted function. This argument is very important, since it determines which objects will be available inside of your function. Usually one of the following two possibilities is the right choice for parent_env:

  • parent_env = .GlobalEnv (default): The global environment is usually the right choice for a function, which does not use any non-exported functions or any imported functions of any R package. This is usually the case, when the function is created outside of any R package (e.g. not inside of a function that is part of some R package).

  • parent_env = "MY_PKG": This is usually the right choice when you are developing a new R package and want to create a restricted function inside of another function of this package (in this example the package name is MY_PKG). This ensures that also non-exported functions and imported functions of MY_PKG are available inside of your restricted function as well as the global environment.

Value

A new function with a small scope containing the variables given in vars.


R-package/styledTables documentation built on Feb. 6, 2024, 2:21 a.m.