I come from python, where import behaves in a more namespaced style, and I have little background with R.
I am trying to develop an R application that is split into separate entities, but as far as I understand, R has no import as in python. From what I gathered:
- library is to import installed libraries, which have their own namespaces so the risk of conflict in the importing .R can be mitigated with
include.only
. - if you have code that is part of your application and not in an external library, you have to use source. From what I gathered, source basically is equivalent of slapping the whole content of the sourced.R file into the sourcing.R file.
I am discussing the second case here. not the first. I suspect that what happens in this case is that if you have multiple sourced.R that have the same symbols, they will conflict silently. From the python point of view, it is pretty much like import *
.
Here are the questions:
- am I correct in saying that the functions defined in sourced.R will all go in the global environment, not in their own environment?
- what happens if you source something twice? does it get included twice?
- is there a technical or best practice solution to prevent accidental conflicts from sourced modules that happen to have the same symbol names?
Edit
This is an example after G. Grothendieck suggestion:
ex1.R
cat("hello")
source("whatever.R")
source("whatever.R", local=whatever <- new.env())
x()
whatever$x()
cat("whatever")
print(environment())
x <- function() {
print("x")
}
So, in principle, one could use this strategy to ensure that functions are not shoved all in the global namespace and conflict. However, it becomes a responsibility of the importing code, and additionally if any state is maintained and two pieces of code source the same module, they will end up with different environments and thus different state.
Bottom line is environments must be stateless.