Function Repository Resource:

SetSymbolsContext

Source Notebook

Set the context for all symbols in an expression

Contributed by: Nikolay Murzin

ResourceFunction["SetSymbolsContext"][expr]

returns expr with all symbols set to the current $Context.

ResourceFunction["SetSymbolsContext"][expr,cont]

uses cont as a new context instead.

Details

Symbols in the System` context are ignored.
In all other cases, only symbols with contexts that are not on $ContextPath are affected.

Examples

Basic Examples (2) 

Set symbols to the current context:

In[1]:=
ResourceFunction["SetSymbolsContext"][{foo`x, bar`y}]
Out[1]=

Set symbols to the specified context:

In[2]:=
ResourceFunction["SetSymbolsContext"][{foo`x, bar`y}, "cxt`"]
Out[2]=

Scope (1) 

Block the $ContextPath to set all the symbols to a different one:

In[3]:=
Block[{$ContextPath = {}}, ResourceFunction["SetSymbolsContext"][f[x, g[y, z]], "cxt`"]]
Out[3]=

Applications (1) 

Retrieve nicer looking definitions from package functions:

In[4]:=
Needs["ComputerArithmetic`"]
In[5]:=
DownValues[ComputerArithmetic`Arithmetic]
Out[5]=
In[6]:=
ResourceFunction["SetSymbolsContext"][
 DownValues[ComputerArithmetic`Arithmetic]]
Out[6]=

Properties and Relations (1) 

SetSymbolsContext is equivalent to ReplaceContext with explicitly constructed replacement rules for all contexts appearing in the expression:

In[7]:=
ResourceFunction["ReplaceContext"][{foo`x, foo`y, bar`z}, {"foo`" -> "baz`", "bar`" -> "baz`"}]
Out[7]=
In[8]:=
ResourceFunction["SetSymbolsContext"][{foo`x, foo`y, bar`z}, "baz`"]
Out[8]=

Possible Issues (2) 

If symbols have definitions in the current context, these definitions are going to be immediately applied on return:

In[9]:=
x = 1;
y = 2;
In[10]:=
ResourceFunction["SetSymbolsContext"][{foo`x, bar`y}]
Out[10]=

Hold the expression to prevent it:

In[11]:=
ResourceFunction["SetSymbolsContext"][Hold[foo`x, bar`y]]
Out[11]=

Version History

  • 1.0.0 – 07 October 2022

Related Resources

License Information