From Mark.Bravington at csiro.au  Mon May  9 03:46:34 2005
From: Mark.Bravington at csiro.au (Mark.Bravington@csiro.au)
Date: Mon May  9 03:46:46 2005
Subject: [Rd] How to understand packages, namespaces, environments
Message-ID: <4D99275E380CA94F998977EDACE548DC062654@extas2-hba.tas.csiro.au>

> On 5/8/05, Mark.Bravington@csiro.au <Mark.Bravington@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


[Rd] How to understand packages, namespaces, environments
Mark.Bravington@csiro.au