I can't quite understand difference between __init__
function and regular code written in module.
So, the problem is the following: I want to store some configuration parameters in a toml file, somewhere in a file system, and I want to read it during using
step. Where should I put initialization steps?
Version №1
module Foo
using TOML
const OPTIONS = Ref(0)
OPTIONS[] = TOML.parsefile("/config.toml")["var"]
end #module
or Version №2
module Foo
using TOML
const OPTIONS = Ref(0)
function __init__()
OPTIONS[] = TOML.parsefile("/config.toml")["var"]
return
end
end #module
Which one is a correct way of initializing variables?
And second question, is there any common Julia path, where I can keep this configuration file? I can do it in ~/.config/...
but I would prefer something more system independent.
Idk if there's a julia version of appdirs but I think that's the platform-agnostic application-agnostic answer to "which directory". Julia itself should use the XDG dirs too but currently doesn't.
The first will run when precompiling the package, the second when using
the package.
Andrey Oskin said:
And second question, is there any common Julia path, where I can keep this configuration file? I can do it in
~/.config/...
but I would prefer something more system independent.
Maybe have a look at https://github.com/JuliaPackaging/Preferences.jl
Thank you, so I suppose I need second, if I want to change settings between runs.
Between restarts, yes.
Thank you.
I do not quite get the idea of Preferences.jl. It can store preferences in LocalPreferences.toml
file of the package. But packages usually have path ~/.julia/packages/Foo/<some random token>/...
where random token is different between package versions. So what, each time I get a new version of the file, my LocalPreferences will be forgotten? It doesn't look convinient.
No that is not how it works, the LocalPreferences.toml
file is stored in your current project, for example:
$ ls
LocalPreferences.toml Manifest.toml Project.toml
$ cat Project.toml
[deps]
Example = "7876af07-990d-54b4-ab0e-23690620f79a"
$ cat LocalPreferences.toml
[Example]
foo = "bar"
And global in Project.toml
of the package?
Yeah, it's not what I really want. I am always running julia with julia --project=.
so each time I have isolated environment.
It is exactly what you want, if you run julia --project=.
it will pick up preferences from the LocalPreferences.toml
file next to your Project.toml
.
But thank you, this package gave me few good ideas.
I guess in my case, I can do the same as thing as PyCall
:
const prefsfile = joinpath(first(DEPOT_PATH), "prefs", "Foo.toml")
mkpath(dirname(prefsfile))
PyCall.jl is moving to Preferences.jl too (https://github.com/JuliaPy/PyCall.jl/pull/945). I don't understand why Preferences.jl is not exactly what you want?
Last updated: Oct 02 2023 at 04:34 UTC