Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a Julia function to a file using the Serialization package?

Tags:

julia

How can I serialize a Julia function object to the disk so it can be later loaded by a different process without sharing the actual source file of that function. Serialization seems to work with lambdas but seems to fail with functions.

using StatsBase, Serialization
flam = (x) -> mean(x) + 1
serialize("flam.ser", flam)

Now I open new Julia session and can deserialize the lambda function:

julia> using StatsBase, Serialization

julia> flam = deserialize("flam.ser")
#1 (generic function with 1 method)

julia> flam(5:7)
7.0

This approach will not work with a function though:

julia> f(x) = mean(x) + 1
f (generic function with 1 method)

julia> serialize("f.ser", f)

Now I try in a new Julia session:

julia> deserialize("f.ser")
ERROR: UndefVarError: #f not defined

How can I serialize the Julia function?

like image 381
Przemyslaw Szufel Avatar asked Oct 23 '25 07:10

Przemyslaw Szufel


1 Answers

If you want for some reason to store serialized functions, you need to serialize methods of a function rather the function itslef. Following the previous code and adding an empty function without methods you could find out that actually no methods got serialized:

julia> function f end
f (generic function with 0 methods)

julia> deserialize("f.ser")
f (generic function with 0 methods)

Hence, we need to serialize methods of a function rather than the function itself:

julia> f(x) = 2*mean(x)
f (generic function with 1 method)

julia> f(x,y) = 4*mean(x) + y
f (generic function with 2 methods)

julia> serialize("f_first_method.ser", methods(f)[1])

julia> serialize("f_all_methods.ser", methods(f))

Now let us start a new Julia session:

julia> function f end
f (generic function with 0 methods)

julia> deserialize("f_first_method.ser")
f(x) in Main at REPL[6]:1

julia> f(6:7)
13.0

julia> deserialize("f_all_methods.ser")
# 2 methods for generic function "f":
[1] f(x) in Main at REPL[6]:1
[2] f(x, y) in Main at REPL[7]:1

julia> methods(f)
# 2 methods for generic function "f":
[1] f(x) in Main at REPL[6]:1
[2] f(x, y) in Main at REPL[7]:1

julia> f(6:7, 0)
26.0

Note that we needed to create an empty function f before starting deserialization of its methods.

like image 155
Przemyslaw Szufel Avatar answered Oct 25 '25 13:10

Przemyslaw Szufel