Namespace Management
In the above examples, the square root function was available from when we first opened up Julia. When we are writing code, this may not be the case, and in fact, we may not want it to be the case. Let’s imagine we want to load a data file from the data/ directory. As seen before, we can do this using the datadir()
function from the {DrWatson}
package. We may not want to load all the functions {DrWatson}
exports into our Main
namespace (one reason being that we may be concerned about a conflict with another package using the same name and argument types, and we want to be explicit about where our function comes from). In this situation, there are two possible solutions:
using DrWatson: datadir; datadir(file.jl)
using DrWatson: DrWatson; DrWatson.datadir(file.jl)
In option 1) we are only loading the datadir()
function into the Main
namespace, but none of the other functions defined and exported by {DrWatson}
. This is a useful compromise when we think we will need to use the datadir()
function multiple times in a file/script as it reduces unnecessarily typing the package name for each function use, while also making it explicit which package the datadir()
function was defined in. In reality, what we are actually calling is Main.datadir()
, as the datadir()
function now belongs to the Main
namespace. Sometimes, though, option 1) isn’t sufficient, such as when we expect a conflict (method ambiguity) to arise.
In option 2), we do not load datadir()
into the Main
namespace, instead, leaving it contained within DrWatson
’s namespace (remember, each package has its own namespace). To use the function, we need to specify that it is defined in the namespace of the {DrWatson}
package, which we do using the package name followed by a period. Much like how we were calling Main.datadir()
in option 1), what we are actually doing is loading the DrWatson
package name into the Main
namespace, and the same syntactic sugar is happening, so option 2) is really calling Main.DrWatson.datadir(file.jl)
. You can think of this as the {DrWatson}
package being treated as a submodule of Main
(see the module section for more information about submodules).