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

(*Out:*)

"Global`"

Although many of the functions we use are not:

Context@Plot

(*Out:*)

"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

(*Out:*)

{"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

(*Out:*)

"NameTools`"

thisIsTheLocalContextPath

(*Out:*)

{"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

(*Out:*)

{"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:

NameTools`hidden`a=100

(*Out:*)

100

a

(*Out:*)

a

a//Context

(*Out:*)

"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]

(*Out:*)

21-7468015508976701203

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

(*Out:*)

100

This just had the current context put in front of the first `

Global`Private`b

(*Out:*)

100

results matching ""

    No results matching ""