Wolfram Computation Meets Knowledge

SerializeWithDefinitions

Contributed by: Richard Hennigan (Wolfram Research)

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

ResourceFunction["SerializeWithDefinitions"][expr]

serializes expr to a ByteArray along with its dependent definitions

Examples

Basic Examples

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

Definitions are restored when deserialized:

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

More Examples

Scope

Retrieve the ResourceFunction:

In[3]:=
ResourceFunction["SerializeWithDefinitions"]
Out[3]=

Retrieve the ResourceObject:

In[4]:=
ResourceObject["SerializeWithDefinitions"]
Out[4]=

Generalizations & Extensions

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

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

BinarySerialize by itself does not preserve definitions:

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

Options

Serialize a Dataset:

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

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

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

Both forms represent the same expression:

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

Applications

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

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

Check the log:

In[18]:=
ReadList[CloudObject["log"]]
Out[18]=

Resource History