Exporting an unwieldy set of constants in a package

折月煮酒 提交于 2019-12-10 11:25:36

问题


I have a package with a nontrivial list of constants I'd like to export to be available to users who load the package. What's the right way of doing so?

The only way I came up with that does what I want is to define the constants in the R code:

a = 1 # (no worries, I'm not using such silly names for the constants)
b = 2
...
z = 26

Then make sure to export them in the NAMESPACE file

export(a, b, c, ..., z)

The problems with this are:

  1. It's quite tedious to type all of the constant names
  2. The list of constants may change over time, and keeping track of exporting the constants in the namespace as well as separately managing their export in the NAMESPACE seems like a chore that's prone to mistakes (i.e., it's not very extensible)

The closest alternative I could come up with that doesn't quite work is to assign the constants to a list within the package, then attach the list:

consts = list(a = 1, b = 2, ..., z = 26)

Then define the .onLoad function appropriately:

.onLoad = function(libname, pkgname) {
  attach(consts)
}

The shortcoming of this is that attach creates a new named environment in the search list; this can add up to namespace cluttering, so I'd prefer the objects be attached to the package environment and then exported there. It seems the hitch with this comes from the NAMESPACE file. The closest thing I've seen to being helpful is the exportPattern function, but unfortunately there's no pattern that's not equivalent to just typing the names of the constants in the first place.

I played around a bit with assign, but the issue of the objects not being exported remains.

How can I overcome these issues so that the following code "just works"?

library(pkg_name)
a + b
# [1] 3 # <- expected output for this example

来源:https://stackoverflow.com/questions/46602925/exporting-an-unwieldy-set-of-constants-in-a-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!