Skip to content

what is the preferred method to create a package local variable?

5 messages · Whit Armstrong, Roger D. Peng, Duncan Murdoch

#
Thanks to everyone for the suggestions.

The package local environment (per Roger Peng) works well.
.localstuff <- new.env()
.localstuff$bbg.db.conn <- dbConnect(...)

However, there is one thing that I'm confused about.

Why must the .localstuff variable be an environment?

I've tried the following, but the variable conn stays null during the
whole R session.  Despite the database connection succeeding (I can
see the constructor printing to the console):

conn <- NULL

.onAttach <- function(libname, pkgname) {
    conn <- dbConnect(dbDriver("PostgreSQL"), user="...")
}

.onUnload <- function(libpath) {
    dbDisconnect(conn)
}

output from R session:

[warmstrong at linuxsvr R.packages]$ R
Loading required package: fts
Loading required package: RCommodity
Loading required package: unifiedDBI
Loading required package: RFincad
Loading required package: RLIM
Loading required package: RBoostDateTime
PostgresConnection::PostgresConnection()
NULL
Error in get.bbg("EURUSD Curncy") : Database connection not initialized
PostgresConnection::~PostgresConnection()
[warmstrong at linuxsvr R.packages]$


Thanks,
Whit






On Tue, Mar 31, 2009 at 3:51 PM, Philippe Grosjean
<phgrosjean at sciviews.org> wrote:
#
The use of an environment gets around the fact that package namespaces
are locked, so that values can't be changed once the package is
loaded. However, elements of environments can be changed.

-roger
On Thu, Apr 2, 2009 at 9:41 AM, Whit Armstrong <armstrong.whit at gmail.com> wrote:

  
    
#
aha!

Now it makes sense.

Thanks, Roger.

-Whit
On Thu, Apr 2, 2009 at 9:49 AM, Roger Peng <rdpeng at gmail.com> wrote:
#
On 4/2/2009 9:41 AM, Whit Armstrong wrote:
If a package doesn't have a namespace, then its functions have their 
environment set to the global environment, so they can stomp on user 
things by accident.   I'd say a better solution to this problem is that 
every package should have a namespace, then there isn't the same risk of 
messing with a user's variables.
That creates a new local variable called conn.  Use

conn <<- dbConnect ...

to modify the package one. (Assuming you have a namespace; if not, that 
will have different effects depending on whether or not the user has a 
variable named conn.  Yecch.)

Duncan Murdoch
#
On 4/2/2009 9:49 AM, Roger Peng wrote:
Oops, I forgot about that.  So use a NAMESPACE plus an environment.

Duncan Murdoch