Assigning result of @load to a variable

Sorry, I am quite new to julia… From looking around, this may be linked to serialization, but I am not sure. In R, I would do (sorry to the R purists, I am one of these “=” <=> “<-” people):

a = 2
saveRDS(a, "example.Rds")
b = readRDS("example.Rds")

I have tried doing the same type of thing in julia

using JLD2
a = 2
@save "example.jld2" a

but then when I @load "example.jld2, it comes with the name a attached (even if I go b = @load...). I don’t want that, I want to assign it to something else right away without manipulation.

To motivate this, one context where this arises is when I am running simulations where the results weigh quite a bit (hundreds of MB to several GB). In the sim code, I use a generic variable name and just change the name of the save file to include some info about the specific sim. In the post-sim code, I just go through the result files, get what info is needed from the file name and process, using again a generic variable name to which I assign the content of whatever file I am using at that point.

I could of course adapt the code to use specific variable names both in and out, but it’s just much easier to go that way. (And saving as csv is either unrealistic in the case of simple variables or not possible for more structured stuff.)

Is there a julia equivalent of my R example?

Just from the Readme:
Why not use b = load("example.jld2")? Or b = load("example.jld2")["a"] if you just want the specific entry?

I think @load is deprecated anyways.

1 Like

The second version is what I am after. I will say “ish”: it works, but it is weird to have to know/find out the name a variable had when it was saved.

Well if you know that this file just contains a single key-value pair you could also just do something like:

first(values(load("example.jld2")))
load("example.jld2") |> values |> first # alternative way of writing the same thing
load("example.jld2") |> first |> first # also works

(Note that also @save is listed under Legacy in the documentation.)

If you want to save the value of a with an explicit name (different than "a"), you can use jldsave("example.jld2", explicit_name=a) or save("example.jld2", "explicit_name", a) to save, and new_var = load("example.jld2")["explicit_name"]) to load.

If you don’t care about the name a is saved under, use save_object("example.jld2", a) and new_var = load_object("example.jld2").

Cool, that’s indeed exactly what I was looking for.