Reference

Configurations.DuplicatedFieldErrorType
DuplicatedFieldError(name, type)

A field with name of given option type is duplicated in the subfields option type. Thus one cannot use the field keyword convention when seeing this error.

source
Configurations.OptionFieldType
OptionField{name}
OptionField(name::Symbol)

Trait type that denotes a field of an option type. Mainly used for dispatch purpose. name should be a Symbol.

source
Configurations.convert_to_optionMethod
convert_to_option(::Type{OptionType}, ::Type{ValueType}, x) where {OptionType, ValueType}

Convert x to type ValueType for option type OptionType. This is similar to Base.convert, but will not error if the conversion is not overloaded, and will return a ConvertNotFound object, but one can use this to avoid type piracy and define contextual conversion based on option types.

Configurations 0.17

This interface is deprecated in favor of from_dict from 0.17.

Example

One may have different string syntax for a Symbol, e.g

@option struct StringIsSymbol
    name::Symbol
end

@option struct SymbolNeedsColon
    name::Symbol
end

Configurations.convert_to_option(::Type{StringIsSymbol}, ::Type{Symbol}, x::String) = Symbol(x)

function Configurations.convert_to_option(::Type{SymbolNeedsColon}, ::Type{Symbol}, x::String)
    if startswith(x, ':')
        Symbol(x[2:end])
    else
        error("expect a Symbol, got String")
    end
end

then if we run it, we will have different behaviour by context.

julia> from_dict(StringIsSymbol, d)
StringIsSymbol(:ccc)

julia> from_dict(SymbolNeedsColon, d)
ERROR: expect a Symbol, got String
source
Configurations.createMethod
create(::Type{T}; kwargs...) where T

Create an instance of option type T from kwargs. Similar to the default keyword argument constructor, but one can use this to create custom keyword argument constructor with extra custom keywords.

source
Configurations.from_dictMethod
from_dict(::Type{T}, d::AbstractDict{String}; kw...) where T

Convert dictionary d to an option type T, the value of valid fields of T in this dictionary d can be override by keyword arguments.

Configurations 0.17

convert_to_option interface is deprecated for conversion, please overload the 3-arg or 4-arg from_dict instead. See also Type Conversion section.

Example

julia> @option struct OptionA
           name::String = "Sam"
           age::Int = 25
       end

julia> d = Dict{String, Any}(
           "name" => "Roger",
           "age" => 10,
       );

julia> from_dict(OptionA, d; age=25)
OptionA(;
    name = "Roger",
    age = 25,
)
source
Configurations.from_dictMethod
from_dict(::Type{OptionType}, ::OptionField{f_name}, ::Type{T}, x) where {OptionType, f_name, T}

For option type OptionType, convert the object x to the field type T and assign it to the field f_name. Raise FieldTypeConversionErrors errors if Base.convert raises exception

ERROR: MethodError: Cannot `convert` an object of type ...
source
Configurations.from_dict_generatedMethod
from_dict_generated(::Type{OptionType}, value::Symbol) where {OptionType}

Generate a specialized Julia expression to convert an AbstractDict{String} to our OptionType.

source
Configurations.from_dict_specializeMethod
from_dict_specialize(::Type{OptionType}, x) where {OptionType}

A specialized from_dict method for option type OptionType. This is usually generated by @option, but one may also specialized this manually to acheive maximal performance.

source
Configurations.from_kwargs!Method
from_kwargs!(d::AbstractDict{String}, ::Type{T}, prefix::Maybe{Symbol} = nothing; kw...) where T

Internal method for inserting keyword arguments to given dictionary object d. It will overwrite existing keys in d if it is specified by keyword argument.

source
Configurations.from_kwargsMethod
from_kwargs(::Type{T}; kw...) where T

Convert keyword arguments to given option type T using the underscore convention.

source
Configurations.from_kwargsMethod
from_kwargs(convention!, ::Type{T}; kw...) where T

Convert keyword arguments to given option type T using convention!. See also from_dict.

Convention

  • from_underscore_kwargs!: use _ to disambiguate subfields of the same name, this is the default behaviour.
  • from_field_kwargs!: do not disambiguate subfields, errors if there are disambiguity
source
Configurations.from_tomlMethod
from_toml(::Type{T}, filename::String; kw...) where T

Convert a given TOML file filename to an option type T. Valid fields can be override by keyword arguments. See also from_dict.

source
Configurations.ignore_extraMethod
ignore_extra(option_type) -> Bool

Return true if the option type ignores extra fields when read from a dict-like object.

Note

Normally, we require the dict-like object to have exactly the same number of fields with the option type. However, it could be useful to have ignore extra fields when wrapping network work services to ignore some irrelavent optional fields.

Note

Unlike pydantic, we do not allow dynamically adding fields to a given type. One should manually define fields you would like to include in a struct type and let it to have type Dict{String, Any}.

Example

julia> Configurations.ignore_extra(::Type{MyOption}) = true
source
Configurations.to_dictMethod
to_dict(x, option::ToDictOption) -> OrderedDict

Convert an object x to an OrderedDict with ToDictOption specified.

Example

to_dict(x, TOMLStyle) # TOML compatible
to_dict(x, YAMLStyle) # YAML compatible
to_dict(x, JSONStyle) # JSON compatible
source
Configurations.to_dictMethod
to_dict(x; include_defaults=true, exclude_nothing=false) -> OrderedDict

Convert an object x to an OrderedDict.

Kwargs

  • include_defaults: include the default value, default is true.
  • exclude_nothing: exclude fields that have value nothing, this supersedes include_defaults when they are both true.

Format Compatibilty

When mapping an option struct from Julia to TOML/YAML/JSON/etc. format, there are some subtle semantic compatibilty one need to deal with, we provide some convenient predefined conversion option constants as TOMLStyle, YAMLStyle, JSONStyle.

Tips

to_dict does not export fields that are of the same values as the defaults. In most cases, this should be the default behaviour, and users should not use include_defaults, however, this can be overridden by changing include_defaults to true.

source
Configurations.to_tomlMethod
to_toml([f::Function], io::IO, option; sorted=false, by=identity, kw...)

Convert an instance option of option type to TOML and write it to IO. See to_dict for other valid keyword options. See also TOML.print in the stdlib for the explaination of sorted, by and f.

Exclude nothing

In TOML specification, there is no null type. One should exclude the field if it is not specified (of value nothing in Julia). In to_toml the option exclude_nothing is always true.

In most cases, nothing is used with another type to denote optional or not specified field, thus one should always put a default value nothing to the option struct, e.g

One should define

@option struct OptionX
    a::Union{Nothing, Int} = nothing
    b::Maybe{Int} = nothing
end

Here Maybe{T} is a convenient alias of Union{Nothing, T}.

source
Configurations.to_tomlMethod
to_toml([f::Function], filename::String, option; sorted=false, by=identity, kw...)

Convert an instance option of option type to TOML and write it to filename. See also TOML.print.

source
Configurations.to_tomlMethod
to_toml(x; sorted=false, by=identity, kw...)

Convert an instance x of option type to TOML and write it to String. See also TOML.print.

to_toml does not export fields that are of the same values as the defaults. This can be overridden by changing include_defaults to true.

source
Configurations.@optionMacro
@option [alias::String] <struct def>

Define an option struct type. This will auto-generate methods that parse a given Dict{String} object (the keys must be of type String) into an instance of the struct type you defined. One can use alias string to distinguish multiple possible option type for the same field.

Special Types

  • Maybe{T}: this type is equivalent to Union{Nothing, T} and is treated specially in @option, it will always have a default value of nothing if not specified.
  • Reflect: this type is treated specially to allow one to use a field to store the corresponding type information.
Configurations 0.16

from v0.16.0 Configurations stops overloading the Base.show method for you, if you need pretty printing of your option types, consider overloading the Base.show(io::IO, mime::MIME, x) method to pprint_struct(io, mime, x) provided by GarishPrint

Configurations 0.12

from v0.12.0 the field alias feature is removed due to the syntax conflict with field docstring. Please refer to #17.

Example

One can define option type via @option macro with or without an alias.

julia> "Option A"
       @option "option_a" struct OptionA
           name::String
           int::Int = 1
       end

julia> "Option B"
       @option "option_b" struct OptionB
           opt::OptionA = OptionA(;name = "Sam")
           float::Float64 = 0.3
       end
julia> option = from_dict(OptionB, d)
OptionB(;
    opt = OptionA(;
        name = "Roger",
        int = 2,
    ),
    float = 0.33,
)

when there are multiple possible option type for one field, one can use the alias to distinguish them

julia> @option struct OptionD
           opt::Union{OptionA, OptionB}
       end

julia> d1 = Dict{String, Any}(
               "opt" => Dict{String, Any}(
                   "option_b" => d
               )
           );

julia> from_dict(OptionD, d1)
OptionD(;
    opt = OptionB(;
        opt = OptionA(;
            name = "Roger",
            int = 2,
        ),
        float = 0.33,
    ),
)
source
Configurations.@type_aliasMacro
@type_alias <type> <name::String>

Define a type alias for option type type. The corresponding type must be a concrete type in order to map this Julia type to a human readable markup language (e.g TOML, YAML, etc.).

source