Mathematica Programming » Code Structure
Contexts
Contexts are a relatively simple concept but have major effects. Their basic use is to tag symbols with extra information. Usually we are in the global context:
$Context
"Global`"
Although many of the functions we use are not:
Context@Plot
"System`"
A context is a series of symbol names followed by "`"
Contexts we can use without fully qualifying the name are those on $ContextPath
$ContextPath
{"CloudObjectLoader`","StreamingLoader`","SymbolicMachineLearningLoader`","IconizeLoader`","HTTPHandlingLoader`","PacletManager`","System`","Global`"}
We can define our own contexts via Begin
and BeginPackage
and the context is exited via End
and EndPackage
respectively. The only difference between these is that BeginPackage
restricts the value of $ContextPath
while Begin
does not:
BeginPackage["NameTools`"];
thisIsTheLocalContextPath=$ContextPath;
EndPackage[]
thisIsTheLocalContextPath//Context
thisIsTheLocalContextPath
"NameTools`"
{"NameTools`","System`"}
This protects symbols from being affected by things in the Global`
context or any other context. Begin
does not do this:
Begin["NameTools`"];
thisIsTheLocalContextPath=$ContextPath;
End[];
thisIsTheLocalContextPath
{"NameTools`","CloudObjectLoader`","StreamingLoader`","SymbolicMachineLearningLoader`","IconizeLoader`","HTTPHandlingLoader`","PacletManager`","System`","Global`"}
Note that BeginPackage
also prepended the context defined to the $ContextPath
.
Anything not in NameTools`
exactly won't be found, however. We can see this by definining something in a subcontext:
NameTools`hidden`a=100
100
And noting that it doesn't get exposed via context in the $ContextPath
:
a
a//Context
a
"Global`"
This is how Mathematica defines so many functions without us having to worry about using the wrong symbols. Just consider all of the symbols we can find in System`Private`
:
Pane[Column@Names@"System`Private`*",
{Automatic,100},Scrollbars->{False,True},
AppearanceElements->None]
One final useful thing to know is that the current context can be implied when defining a symbol, such as done in the following example:
`Private`b=100
100
This just had the current context put in front of the first `
Global`Private`b
100