Roger-luo / Configurations.jl

Options & Configurations made easy.
https://configurations.rogerluo.dev/stable
MIT License
80 stars 12 forks source link

Allow check config when defining structs? #12

Closed singularitti closed 3 years ago

singularitti commented 3 years ago

Sometimes I want to check whether the input config is valid. This requires a redefinition of the constructors. The current implementation does not seem to support that.

julia> @option "pressures" struct Pressures
           values::AbstractVector
           unit::String = "GPa"
       end

julia> function Pressures(values::AbstractVector, unit::String)
           if length(pressures) <= 5
               @info "pressures <= 5 may give unreliable results, consider more if possible!"
           end
           if minimum(pressures) >= zero(eltype(pressures))
               @warn "for better fitting, we need at least 1 negative pressure!"
           end
           unit == "x" && error("wrong unit!")
           return Pressures(values, unit)
       end
Pressures

julia> Pressures(1:2, "GPa")
ERROR: UndefVarError: pressures not defined
Stacktrace:
 [1] Pressures(values::UnitRange{Int64}, unit::String)
   @ Main ./REPL[3]:2
 [2] top-level scope
   @ REPL[4]:1

Can we define @check & @check_no_err etc.? Like @assert in Parameters? However, I don't think @assert is a good option because it will error when the conditions are not satisfied, but sometimes we just want to warn the users.

Roger-luo commented 3 years ago

Sometimes I want to check whether the input config is valid. This requires a redefinition of the constructors. The current implementation does not seem to support that.

not sure what you mean, but you code doesn't work itself

singularitti commented 3 years ago

What I mean is that I want to add some checks when constructing the config type. Like the following pseudocode:

@option "pressures" struct Pressures
    values::AbstractVector
    unit::String = "GPa"
    function Pressures(values::AbstractVector, unit::String)
        if length(pressures) <= 5
            @info "pressures <= 5 may give unreliable results, consider more if possible!"
        end
        if minimum(pressures) >= zero(eltype(pressures))
            @warn "for better fitting, we need at least 1 negative pressure!"
        end
        unit == "x" && error("wrong unit!")
        return new(values, unit)
    end
end
Roger-luo commented 3 years ago

Your pseudocode is not valid Julia code, you didn't define what's pressures

Roger-luo commented 3 years ago

the error has been very clear

ERROR: UndefVarError: pressures not defined
Stacktrace:
 [1] Pressures(values::UnitRange{Int64}, unit::String)
   @ Main ./REPL[3]:2
 [2] top-level scope
   @ REPL[4]:1
singularitti commented 3 years ago

My bad, I forgot to change the variable names. It seems to work, thank you.