Function Repository Resource:

ContextModule

Source Notebook

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

Contributed by: Richard Hennigan (Wolfram Research)

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 (3) 

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 (2) 

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

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

Apply Compress to an expression so that it is 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 (2) 

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 (2) 

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 11 October 2018

Related Resources

License Information