Reference
Configurations.JSONStyle — ConstantJSONStyle::ToDictOptionPredefined option for JSON compatible to_dict option.
Configurations.Maybe — Typemaybe of type T or nothing
Configurations.TOMLStyle — ConstantTOMLStyle::ToDictOptionPredefined option for TOML compatible to_dict option.
Configurations.YAMLStyle — ConstantYAMLStyle::ToDictOptionPredefined option for YAML compatible to_dict option.
Configurations.ConvertNotFound — TypeConvertNotFoundConversion is not defined via convert_to_option. One should let the conversion fallback to Base.convert when see this.
Configurations.DuplicatedFieldError — TypeDuplicatedFieldError(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.FieldTypeConversionError — TypeFieldTypeConversionError(type, fieldname, fieldtype, optiontype)A conversion from type to fieldtype belonging to fieldname in an optiontype failed.
Configurations.OptionField — TypeOptionField{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.PartialDefault — TypePartialDefault{F}Type for non-constant default value, it depends on the value of another field that has default value.
Configurations.alias_map — Methodalias_map(types::Vector{Any})Create a Dict mapping type alias to a type.
Configurations.compare_options — Methodcompare_options(a, b, xs...)::BoolCompare option types check if they are the same.
Configurations.convert_to_option — Methodconvert_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.
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
endthen 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 StringConfigurations.create — Methodcreate(::Type{T}; kwargs...) where TCreate 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_default — Methodfield_default(::Type{T}, name::Symbol)Return the default value of field name of an option type T.
Configurations.field_defaults — Methodfield_defaults(::Type)Return default values of given option types.
Configurations.field_keywords — Methodfield_keywords(::Type{T}) where TReturn all the option type field names given T, error if there are duplicated sub-fields.
Configurations.from_dict — Methodfrom_dict(::Type{T}, d::AbstractDict{String}; kw...) where TConvert dictionary d to an option type T, the value of valid fields of T in this dictionary d can be override by keyword arguments.
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_dict — Methodfrom_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_generated — Methodfrom_dict_generated(::Type{OptionType}, value::Symbol) where {OptionType}Generate a specialized Julia expression to convert an AbstractDict{String} to our OptionType.
Configurations.from_dict_specialize — Methodfrom_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_kwargs — Methodfrom_field_kwargs(::Type{T}; kw...) where TConvert keyword arguments to given option type T using the field keyword convention.
Configurations.from_kwargs! — Methodfrom_kwargs!(d::AbstractDict{String}, ::Type{T}, prefix::Maybe{Symbol} = nothing; kw...) where TInternal 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_kwargs — Methodfrom_kwargs(::Type{T}; kw...) where TConvert keyword arguments to given option type T using the underscore convention.
Configurations.from_kwargs — Methodfrom_kwargs(convention!, ::Type{T}; kw...) where TConvert 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_toml — Methodfrom_toml(::Type{T}, filename::String; kw...) where TConvert 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_exists — Methodfrom_toml_if_exists(::Type{T}, filename::String; kw...) where TSimilar to from_toml but will create the option instance via from_kwargs(T;kw...) instead of error if the file does not exist.
Configurations.from_underscore_kwargs — Methodfrom_underscore_kwargs(::Type{T}; kw...) where TConvert keyword arguments to given option type T using the underscore convention.
Configurations.has_same_reflect_field — Methodhas_same_reflect_field(types::Vector{Any})Check if all types has the same reflect field name.
Configurations.ignore_extra — Methodignore_extra(option_type) -> BoolReturn true if the option type ignores extra fields when read from a dict-like object.
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.
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}) = trueConfigurations.is_option — Methodis_option(x)Check if x is an option type or not.
Configurations.is_option_maybe — Methodis_option_maybe(::Type{T}) where TT is an option struct or if T is an union, one of the types is an option struct.
Configurations.to_dict — Methodto_dict(x, option::ToDictOption) -> OrderedDictConvert 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 compatibleConfigurations.to_dict — Methodto_dict(x; include_defaults=true, exclude_nothing=false) -> OrderedDictConvert an object x to an OrderedDict.
Kwargs
include_defaults: include the default value, default istrue.exclude_nothing: exclude fields that have valuenothing, this supersedesinclude_defaultswhen they are bothtrue.
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.
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_toml — Methodto_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
endHere Maybe{T} is a convenient alias of Union{Nothing, T}.
Configurations.to_toml — Methodto_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_toml — Methodto_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.type_alias — Methodtype_alias(::Type{OptionType}) -> StringReturn the alias name of given OptionType.
Configurations.underscore_keywords — Methodunderscore_keywords(::Type{T}) where TReturn keywords given T using the underscore convention.
Configurations.@option — Macro@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 toUnion{Nothing, T}and is treated specially in@option, it will always have a default value ofnothingif not specified.Reflect: this type is treated specially to allow one to use a field to store the corresponding type information.
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
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_alias — Macro@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.).