[Rd] How to understand packages, namespaces, environments

Mark.Bravington at csiro.au Mark.Bravington at csiro.au
Mon May 9 03:46:34 CEST 2005


> On 5/8/05, Mark.Bravington at csiro.au <Mark.Bravington at csiro.au> wrote:
> > [Alexander Stoddard]
> > > Subject: Re: [Rd] How to understand packages, namespaces, 
> > > environments
> > >
> > > >
> > > > Does saying the following load package 'foo' into its own
> > > environment ?
> > > >  > library(foo)
> > >
> > [Duncan Murdoch]
> > > This loads some of the (name, object) pairs from the package into 
> > > two
> > > environments:  the public one the user can see, and the namespace 
> > > one that the code in the package can see.  They're related, you 
> > > don't get two copies of the objects.
> >
[MVB] 
> > That's interesting-- I thought there really were two copies. In my 
> > debug package, I've taken the approach of changing both copies.
> 
[Gabor Grothendieck]
> How does one refer to the two different copies? Thanks.
> 
> 

The help for fun.locator (in the debug package) contains my
interpretation of what's going on (which might be wrong, but seems to
work). A slightly simplified version of the guts of fun.locator is as
follows:

  # function to check for something called fname
  is.here <- function( env) exists( fname, env=env, inherits=FALSE)

  # Search path
  search.envs <- lapply( 1:length( search()), pos.to.env)
  ff <- search.envs[ sapply( search.envs, is.here)]
 
  # Hidden namespace environments
  ln <- lapply( loadedNamespaces(), asNamespace)
  ff <- c( ff, ln[ sapply( ln, is.here)]) 
  
  # S3 methods:
  S3 <- lapply( ln, function( x) if( exists( '.__S3MethodsTable__.', x,
inherits=FALSE)) 
    get( '.__S3MethodsTable__.', x) else 0)
  S3 <- S3[ !sapply( S3, is.numeric)]
  ff <- c( ff, S3[ sapply( S3, is.here)])

Then ff is a list of environments where a copy (?) of fname exists-- and
you can use
 ff[[i]][[fname]] 
or 
 get(fname, env=ff[[i]]) & assign( fname, ..., env=ff[[i]])

I should point out that the doco for asNamespace says "not intended to
be called directly"-- but I couldn't see an alternative, and anyway it
seems to work (for now).

Mark



More information about the R-devel mailing list