Serialize and deserialize generic functions

168 views
Skip to first unread message

Cristóvão Duarte Sousa

unread,
Jan 28, 2014, 1:32:29 AM1/28/14
to julia...@googlegroups.com
Hi,

I would like to do something like

f(x) = x+1
open("f.jld", "w") do file
    serialize(file, f)
end

then, close julia, open it again and do

open("f.jld", "r") do file
    f = deserialize(file)
end
f(1)

but that gives "ERROR: f not defined"


Is serialization supposed to be able to do this?
If yes, which is the right way to code it?

Thanks

Ivar Nesje

unread,
Jan 28, 2014, 5:25:37 AM1/28/14
to julia...@googlegroups.com
This does not solve your problem, but you will get closer if you declare f as global so that you do not write to a local variable that will go out of scope as soon as it gets declared.

open("f.jld", "r") do file
    global f = deserialize(file)
end
f(1)
ERROR: function f not defined on process 1
in error at error.jl:21
in anonymous at serialize.jl:353

I am not sure how deserialization of functions is intended to work, so this is all I could do.

Cristóvão Duarte Sousa

unread,
Jan 28, 2014, 5:20:30 PM1/28/14
to julia...@googlegroups.com
Thanks Ivar for pointing that error of mine. I'd previously written the deserialize in the main scope and got the same "function f not defined on process 1", but then I rewrite it inside the `do` block without noticing it introduces another scope.

So the real ERROR is the one you presented.

Meanwhile I worked around this issue by serializing not the function but its Expression which is evaluated after the deserialization.
However, I still wonder if it is possible to do something like what I was trying.

Stefan Karpinski

unread,
Jan 28, 2014, 6:11:54 PM1/28/14
to Julia Users
You can use the fact that open returns the value of the block:

f = open("f.jld", "r") do file
    deserialize(file)
end

Cristóvão Duarte Sousa

unread,
Jan 28, 2014, 6:14:11 PM1/28/14
to julia...@googlegroups.com
Hum, nice. Thanks.
Reply all
Reply to author
Forward
0 new messages