Namespaces without packages
module, namespaces, r
Solution
I’ve implemented a comprehensive solution and published it as a package, ‘box’.
Internally, ‘box’ modules uses an approach similar to packages; that is, it loads the code inside a dedicated namespace environment and then exports selected symbols into a module environment which is returned to the user, and optionally attached. The main difference to packages is that modules are more lightweight and easier to write (each R file is its own module), and can be nested.
Usage of the package is described in detail on its website.
Problem
In reorganising my code base I’d like to clean up my code sharing mechanism. So far I’m using `source` for lots of small, largely self-contained modules of functionality. However, this approach suffers from a number of problems, among them - the lack of tests for circularity (accidental circular `source` chains), - complex syntax required to properly specify include paths (`chdir=TRUE` argument, hard-coded paths), - potential of name clashes (when redefining objects). Ideally I’d like to get something alike to the Python module mechanism. The R package mechanism would be overkill here: I do not want to generate nested path hierarchies, multiple files with tons of metadata and manually build the package just to get a small, self-contained, reusable code module. For now I’m using a code snippet which allows me to solve the first two problems mentioned above. The syntax for inclusion is like this: ``` import(functional) import(io) import(strings) ``` … and a module is defined as a simple source file which resides in the local path. The definition of `import` is straightforward but I cannot solve the third point: I want to import the module into a separate namespace but from what I see the namespace lookup mechanism is pretty hard-wired to packages. True, I could override ``::`` or `getExportedValue` and maybe `asNamespace` and `isNamespace` but that feels very dirty and has the potential of breaking other packages.