10.2 Namespace
10.2.1 Motivation
- Namespace provides context for looking up value of an object associated with a name.
- Example:
::operator:
library(lubridate) | library(here)
library(here) | library(lubridate)
here() # here::here() | here() # lubridate::here()- Recommended to use
package::function()for dependencies in code belowR/ - Package namespace saves us from potential user redefinitions of functions
- (There are other ways than using
::to address potential name conflicts.)
10.2.2 The NAMESPACE file
Example:
# Generated by roxygen2: do not edit by hand
S3method(compare,character)
S3method(print,testthat_results)
export(compare)
export(expect_equal)
import(rlang)
importFrom(brio,readLines)
useDynLib(testthat, .registration = TRUE)
Each line contains a directive:
export(): export a function (including S3 and S4 generics).S3method(): export an S3 method.importFrom(): import selected object from another namespace (including S4 generics).import(): import all objects from another package’s namespace. package.useDynLib(): registers routines from a DLL.
Each line is generated by roxygen2. This method is preferred because:
- Namespace tags are integrated into source code
- Only need to learn
@exportand roxygen2 figures out the specific directive - Roxygen2 takes on the burden of writing
NAMESPACEin a neat and tidy manner