wahani / modules

Modules in R
https://cran.r-project.org/package=modules
Other
81 stars 3 forks source link

Export from a list of objects #20

Open mmuurr opened 4 years ago

mmuurr commented 4 years ago

At times it's useful, even within a module, to keep objects cleanly-organized with each other in lists. modules doesn't seem to like when we try to export an object that's stored in a list, however. (Though it does just fine at exporting the entire list.) Here's an example module.R file:

my_exports <- list()
my_exports$f1 <- function() "f1"
my_exports$f2 <- function() "f2"
modules::export(f1 = my_exports$f1, f2 = my_exports$f2)  ## this errors

The above example uses explicit export naming, which is brought up as a separate issue here (#19).

It could also be nice to simply export all objects in a list, as I naïvely tried when experimenting with modules, e.g. the export call in the example above could be imagined like so:

do.call(modules::export, my_exports)

... i.e. where my_exports in the example is a named list of objects to export. I realize this introduces the error-handling behavior of 'what to do if there are unnamed list elements' ... I'd propose failing-fast in that case.

Perhaps a separate export wrapper function entirely that necessitates named elements? (Or even an option, like .require_name = <TRUE/FALSE> that forces naming behavior?)

wahani commented 4 years ago

As a solution to this, I would suggest to use sub-modules and modules::expose. This would look something along the lines of:

m <- modules::module({
  .sm <- modules::module({
    foo <- function() "foo"
  })
  bar <- function() "bar"
  modules::expose(.sm, "foo")
})

m$foo()
m$bar()

If we had something like the renaming of exports, that would replace the need for expose. Would this pattern be applicable to your use cases?

It could also be nice to simply export all objects in a list, as I naïvely tried when experimenting with modules, e.g. the export call in the example above could be imagined like so:

This should be possible if we allow for renaming exports, i.e. export(f = foo), at least it should be one of the unit tests.

wahani commented 4 years ago

Renaming of exports is implemented in #21 and part of #19. Exporting lists will not be easy to implement due to the current export mechanism. It simply follows a different idea. It can be achieved as demonstrated above.