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.

Configurations.FieldTypeConversionErrorType
FieldTypeConversionError(type, fieldname, fieldtype, optiontype)

A conversion from type to fieldtype belonging to fieldname in an optiontype failed.

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.

Configurations.PartialDefaultType
PartialDefault{F}

Type for non-constant default value, it depends on the value of another field that has default value.

Configurations.ReflectType
Reflect

Placeholder type for reflected type string.

Type Alias

if the corresponding type has a type_alias defined, serialization and parsing will use the type_alias instead of the type name, this only works on concrete types since the alias cannot contain any type var information.

Example

the following option struct

@option struct MyOption
    type::Reflect
    name::String = "Sam"
end

would be equivalent to

type = "MyOption"
name = "Sam"

this is useful for defining list of different types etc.

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
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.

Configurations.field_keywordsMethod
field_keywords(::Type{T}) where T

Return all the option type field names given T, error if there are duplicated sub-fields.

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,
)
Configurations.from_dictMethod
from_dict(::Type{OptionType}, ::Type{T}, x) where {OptionType, T}

For option type OptionType, convert the object x to type T. This is similar to Base.convert(::Type{T}, x) and will fallback to Base.convert if not defined.

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 ...
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.

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.

Configurations.from_field_kwargsMethod
from_field_kwargs(::Type{T}; kw...) where T

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

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.

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

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

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
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.

Configurations.from_toml_if_existsMethod
from_toml_if_exists(::Type{T}, filename::String; kw...) where T

Similar to from_toml but will create the option instance via from_kwargs(T;kw...) instead of error if the file does not exist.

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
Configurations.is_option_maybeMethod
is_option_maybe(::Type{T}) where T

T is an option struct or if T is an union, one of the types is an option struct.

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
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.

Configurations.to_dictMethod
to_dict(::Type{T}, x, option::ToDictOption) where T

Convert x when x is inside an option type T. option is a set of options to determine the conversion behaviour. this can be overloaded to change the behaviour of to_dict(x; kw...).

to_dict(::Type{T}, x) where T

One can also use the 2-arg version when x is not or does not contain an option type for convenience.

Example

The following is a builtin overload to handle list of options.

function Configurations.to_dict(::Type{T}, x::Vector, option::ToDictOption) where T
    if is_option(eltype(x))
        return map(p->to_dict(T, p, include_defaults), x)
    else
        return x
    end
end

The following overloads the 2-arg to_dict to convert all VersionNumber to a String for all kinds of option types.

Configurations.to_dict(::Type, x::VersionNumber) = string(x)
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}.

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.

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.

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,
    ),
)
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.).