[Rd] How to override functions in namespaces?

Duncan Murdoch murdoch at stats.uwo.ca
Fri Feb 23 00:24:48 CET 2007

On 2/12/2007 1:13 PM, jhallman at frb.gov wrote:
> In package A I have askForString(), which asks the user for a string.
> Also in package A I have defined ssh(), which calls askForString().
> Package B has package A as a prerequisite.
> In package B I redefine askForString() to take advantage of a nicer user
> interface made available by B, namely the Emacs mini-buffer prompt.
> Packages B and A are both on the search path, with B ahead of A.  If I
> call askForString() at the command prompt, I get the version from B.
> But the version used by ssh() depends on whether or not package A has a
> namespace. If so, ssh() (defined in A) always uses the A version of
> askForString().  How can I get ssh() to use the B version of
> askForString()? Or am I going about this all wrong?

There are several ways.  If package A "knows" that some users will want 
to replace askForString(), then it should allow the user to tell it what 
to use for that function, and fall back to its own definition as a 
default.  It could do this by explicitly looking for askForString in the 
global environment (which will fall back to the search list if not 
found), or it could get the function from an option() setting, etc.

If package A doesn't expect askForString() to be changed, then you 
shouldn't change it:  you might break something else in A.  You should 
write to the author of A (which sounds as though it's yourself), and ask 
for some improvements to the package.

There are dirty methods to modify the contents of a namespace, but you 
shouldn't use those.

Duncan Murdoch

More information about the R-devel mailing list