Function Repository Resource:

SerializeWithDefinitions

Source Notebook

Serialize an expression along with any needed definitions so that it can be used in another session

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["SerializeWithDefinitions"][expr]

serializes expr to a ByteArray along with its dependent definitions.

Examples

Basic Examples (2) 

Serialize an expression with dependent definitions:

In[1]:=
ClearAll[f, g];
f[x_] := g[x] + 1;
g[x_] := 2 x;
bytes = ResourceFunction["SerializeWithDefinitions"][f]
Out[4]=

Definitions are restored when the expression is deserialized:

In[5]:=
ClearAll[f, g];
BinaryDeserialize[bytes][5]
Out[6]=

Generalizations and Extensions (2) 

The serialized expression is an evaluation that restores definitions before returning the output:

In[7]:=
ClearAll[f, g];
f[x_] := g[x] + 1;
g[x_] := 2 x;
bytes = ResourceFunction["SerializeWithDefinitions"][f];
In[8]:=
BinaryDeserialize[bytes, HoldForm]
Out[8]=

BinarySerialize by itself does not preserve definitions:

In[9]:=
b1 = BinarySerialize[Unevaluated[f[5]]]
Out[9]=
In[10]:=
b2 = ResourceFunction["SerializeWithDefinitions"][Unevaluated[f[5]]]
Out[10]=
In[11]:=
ClearAll[f, g];
In[12]:=
BinaryDeserialize[b1]
Out[12]=
In[13]:=
BinaryDeserialize[b2]
Out[13]=

Options (3) 

Serialize a Dataset:

In[14]:=
bin = ResourceFunction["SerializeWithDefinitions"][
  ExampleData[{"NetworkGraph", "AstrophysicsCollaborations"}]]
Out[14]=

Serialize the same Dataset with PerformanceGoal set to "Size":

In[15]:=
compressed = ResourceFunction["SerializeWithDefinitions"][
  ExampleData[{"NetworkGraph", "AstrophysicsCollaborations"}], PerformanceGoal -> "Size"]
Out[15]=

Both forms represent the same expression:

In[16]:=
BinaryDeserialize[bin] == BinaryDeserialize[compressed]
Out[16]=

Applications (2) 

CloudPut an evaluation that runs each time you use use CloudGet on it:

In[17]:=
CloudSymbol["count"] = 0;
info[] := With[{i = <|"Time" -> Now, "Count" -> (CloudSymbol["count"] += 1)|>}, PutAppend[i, CloudObject["history"]]; i];
In[18]:=
With[{b = ResourceFunction["SerializeWithDefinitions"][
    Unevaluated[info[]]]},
 CloudPut[Unevaluated[BinaryDeserialize[b]], "info"]
 ]
Out[18]=
In[19]:=
CloudGet["info"]
Out[19]=
In[20]:=
CloudGet["info"]
Out[20]=

Check the log:

In[21]:=
ReadList[CloudObject["history"]]
Out[21]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 15 August 2018

Related Resources

License Information