This is a cross post from https://discourse.julialang.org/t/retrieving-an-instance-of-an-enum-using-a-string/61183/7 . That may be of interest here too
@enum LogLevel begin
LL_INFO
LL_DEBUG
end
Please also note from
Base.tryparse(E::Type{<:Enum}, str::String) =
let insts = instances(E) ,
p = findfirst(==(Symbol(str)) ∘ Symbol, insts) ;
p !== nothing ? insts[p] : nothing
end
using Test
@testset "now" begin
@test tryparse(LogLevel, "LL_INFO") == LL_INFO
@test tryparse(LogLevel, "ll_info") == nothing
@test tryparse(LogLevel, "INFO") == nothing
@test tryparse(LogLevel, "info") == nothing
end
Those possibles evolutions :
Base.tryparse(E::Type{<:Enum}, str::String; prefix::String="") =
let eq(x, e) = lowercase(prefix*x) == lowercase(e) ,
# eq could be statically dispatchable according to some enum surface lang traits
insts = instances(E) ,
p = findfirst(insts .|> string) do e; eq(str,e) end;
p !== nothing ? insts[p] : nothing
end
@testset "meanwhile" begin
@test tryparse(LogLevel, "LL_INFO") == LL_INFO
@test tryparse(LogLevel, "ll_info") == LL_INFO
@test tryparse(LogLevel, "INFO"; prefix="LL_") == LL_INFO
@test tryparse(LogLevel, "info"; prefix="LL_") == LL_INFO
end
particulaly considering Solving the drawbacks of @enum