evaluation - How to properly DumpSave & Get Global`s symbols inside packages while not touching Global context?
For efficiency reasons I prefer to use DumpSave
instead of Save
.
For ease of access I prefer to save symbols in DumpSaved
files inside Global` context.
But when my code evolved and I moved it inside packages I found a lot of problems to read symbols from those DumpSaved
files so that read & write process
- allows for use saved variables inside my package (and its context)
- does not affect variables in
Global`
- When user loads the file directly with
Get
, bypassing my package (and perhaps not even loading it), the symbol is available inGlobal`
context for him or her - symbol name is not hard-coded into function (but of course it must hard-coded into the file itself :-( )
Simply put: I want to use DumpSave
& Get
the way I use Export
& Import
, but with efficiency and flexibility benefits.
I come up with the following code, but it still messes the Global context and has the symbol name hardcoded (Global`myglobalname
):
SaveMySymbol[object_,path_String]:= Block[{},
OwnValues[Global`myglobalname] = HoldPattern[Global`myglobalname] :> object;
DumpSave[
path<>".mx", Global`myglobalname]];
LoadMySymbol[path_String]:= Block[{strfullpath},
strfullpath = path<>".mx";
If[FileExistsQ[strfullpath], Get[strfullpath]; Global`myglobalname,
Null]]
I guess the problem with messing the Global`
context can be avoided by caching the maybe existing definition of Global`myglobalname
symbol and returning it back after Get
. But the code look already awfully complex (it took me a full day to figure out the trick with OwnValues
) and I suspect that there must be an easy way... Well, so far there always was one with Mathematica...
Answer
To show how this is possible:
Simply put: I want to use
DumpSave
&Get
the way I useExport
&Import
, but with efficiency and flexibility benefits.
You can simply use Import
and Export
. They do support the same format that DumpSave
uses, and they give you the same performance. But they don't save symbol names.
Export["data.mx", data, "MX"]
data = Import["data.mx"]
MX files are not portable between architectures though, so you may consider using Compress
ed strings, as described here. This is several times slower, but it's still quite fast compared to any other alternative and it's portable.
If you ever need to save InterpolatingFunction
s, please be aware of this problem.
Comments
Post a Comment