Is it dangerous to create a namespace for functions in a script without a package?

Hi everyone,

Consider the following function:

source_as_ns <- function(namespace, file){
  ns <- namespace::makeNamespace(namespace)
  source(file, local = ns)
  base::namespaceExport(ns, ls(ns))

It creates a namespace containing objects defined in the R script file. So:

# script.R
foo <- function(x) x + 1
source_as_ns("bar", "script.R")

# 2

Apart from the "why not using a package/namespace" points, are there other reasons not to use a function like this to avoid polluting the Global Env. and have the functions in the script available for use?


1 Like

If you're only doing this locally on your system, it's completely up to you. However, there would obviously be a few things to consider.

  1. What packages the functions in the namespace rely on, you'd have to ensure these are loaded further up the search() path.
  2. Where on the search() path this is going to go, and how will that effect any packages loaded after your new namespace.
  3. Naming conflicts: make sure your new namespace is unique (maybe check that the new name doesn't match any other packages).
  4. How would this behave if ran on a different system?

There are probably plenty of other questions that you should ask before implementing something like this in a workflow. But if it works for you, go for it.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.