I made a small package Configurations.jl to separate the utilities we wrote for Pluto.jl and Comonicon.jl for parsing configurations/options from TOML files and kwargs and serialize them back. (there are still 3 days left until it’s registered in General)
Why?
In quite a lot cases, we will want to read configurations from a TOML/JSON/YAML/XML file, such as Web applications, CLI applications, or just some ML research project that needs to specify a fairly large set of hyper-parameters. This is usually done via the following steps:
- parse the configurations:
- it can be a file and parsed via a corresponding parser, e.g TOML.jl, YAML.jl JSON.jl etc. to a
Dict
- it can be kwargs from some function
- it can be a file and parsed via a corresponding parser, e.g TOML.jl, YAML.jl JSON.jl etc. to a
- define a set of Julia
struct
s as an intermediate representation to make further processing easier - convert this
Dict
or kwargs object to thestruct
s we just defined - propagate these configurations
struct
instances to places use them - some times, the configurations may get edited either interactively or programatically, we may need to serialize them back to
Dict
or a TOML file etc.
I personally find these steps repeats quite frequently in a lot packages I participate, and I kept creating similar things.
How to use
this package exports a macro called @option
it is similar to Base.@kwdef
but it defines some extra methods to help you create types for configurations, e.g we have two configurations types
using Configurations
@option struct Person
name::String = "John"
age::Int = 20
end
@option struct User
person::Person = Person()
tag::String = "none"
is_something::Bool = false
end
first we want to read our configuration from a TOML file example.toml
:
tag = "red"
is_something = true
[person]
name = "Roger"
age = 25
we can just call
from_toml(User, "example.toml")
on the other hand, you might still want to have a keyword argument interface for interactive usage,
you can just call from_kwargs
to convert it from keyword arguments, the keyword arguments are auto-generated to handle hierarchical structures in a flattened manner:
from_kwargs(User; person_name = "Roger", person_age = 20, is_something = true, tag = "Blue")
In the end, you can serialize this configuration back to TOML, via to_toml
or convert it back to OrderedDict
via to_dict
.
Have fun!