What is the benefit of import in a namespace in R?
Solution 1:
If a function foo
is imported from package Bar then it is found regardless of what the user does to their search path, e.g., by attaching a package Baz that also has a function foo
. Without a name space, the package code would suddenly find itself using Baz::foo
. There are also efficiency issues (foo
is found immediately, rather than after searching through all symbols on the search path), but these are likely to be trivial for most applications. In the same way, importFrom
is an improvement over import
because of fewer collisions (or use of unintended functions) and more efficient look-up.
With S4 (and S3) things can get quite complicated. A non-generic function like graphics::plot
can be promoted to a generic (with setGeneric
) in two different packages, and each generic can have its own set of methods attached. A package author will want to be precise about which plot
generic, and hence which methods dispatch table, their classes and methods see.
Calling a function with pkg::foo
always resolves to the intended function. It requires that pkg be listed in the Depends: field of the DESCRIPTION file (maybe in Imports: but then it seems like misleading advertising to not import from pkg), polluting the user's search path. It also involves two symbol look-ups and a function call (::
), and so is less efficient. The lazy and lack-of-attention-to-detail part of me also sees use of ::
as tedious and error prone.
The package codetoolsBioC (via svn with username and password readonly
) can generate a NAMESPACE file from an existing package (or at least it could before recent changes to R-devel introduced a NAMESPACE on packages without one; I haven't tried codetoolsBioC on such a package).