Wolfram Computation Meets Knowledge

ContextModule

Contributed by: Richard Hennigan (Wolfram Research)

Temporarily set $Context and $ContextPath to a unique empty context for an evaluation

ResourceFunction["ContextModule"][expr]

evaluates expr with $Context and $ContextPath set to an empty temporary context.

Details and Options

Any symbols created in the temporary context will be removed.

Examples

Basic Examples

Temporarily use an empty context:

In[1]:=
ResourceFunction["ContextModule"][$Context]
Out[1]=

The $ContextPath is also changed:

In[2]:=
ResourceFunction["ContextModule"][$ContextPath]
Out[2]=

The values of $Context and $ContextPath are restored after evaluation of ContextModule:

In[3]:=
$Context
Out[3]=
In[4]:=
$ContextPath
Out[4]=

Applications

Put an expression to a file with fully qualified symbol names:

In[5]:=
ResourceFunction["ContextModule"][Put[a + b, file = CreateFile[]]]
In[6]:=
FilePrint[file]

Compress an expression so that it's not dependent on the current context:

In[7]:=
$ContextPath = Append[$ContextPath, "MyContext`"];
compressed = ResourceFunction["ContextModule"][
  Compress[MyContext`x + MyContext`y]]
Out[8]=

This ensures that contexts are preserved when uncompressed in another session:

In[9]:=
CloudEvaluate[Uncompress[compressed, ToString]]
Out[9]=

Without ContextModule, the symbols would take on whatever the current context is when uncompressed:

In[10]:=
compressed = Compress[MyContext`x + MyContext`y]
Out[10]=
In[11]:=
CloudEvaluate[Uncompress[compressed, ToString]]
Out[11]=

Properties and Relations

ContextModule always uses an empty context:

In[12]:=
ResourceFunction["ContextModule"][Names[__]]
Out[12]=

ContextModule is similar to Module in the sense that symbols created during the evaluation are not permanent:

In[13]:=
Module[{x}, ResourceFunction["FullSymbolName"][x]]
Out[13]=
In[14]:=
NameQ[%]
Out[14]=
In[15]:=
ResourceFunction["ContextModule"][
 With[{x = Symbol["x"]}, ResourceFunction["FullSymbolName"][x]]]
Out[15]=
In[16]:=
NameQ[%]
Out[16]=

Possible Issues

Any symbols created in the temporary context are removed when the evaluation completes:

In[17]:=
ResourceFunction["ContextModule"][Symbol["x"]]
Out[17]=

This also restores Contexts:

In[18]:=
old = Contexts[];
ResourceFunction["ContextModule"][
  Symbol["y"];
  new = Contexts[]
  ];
Contexts[] === old
Out[20]=
In[21]:=
Complement[new, old]
Out[21]=

Resource History