# Retrieving an instance of an enum using a string

**URL:** https://discourse.julialang.org/t/retrieving-an-instance-of-an-enum-using-a-string/61183
**Category:** General Usage
**Tags:** enum
**Created:** [May 15, 2021, 3:33am UTC](https://discourse.julialang.org/t/retrieving-an-instance-of-an-enum-using-a-string/61183 "2021-05-15T03:33:25Z")
**Posts on this page:** 1
**Showing post:** 7

<div class="post-metadata">

### Author: ![o314](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/o314/32/252_2.png) [@o314](https://discourse.julialang.org/u/o314)
#### Post date: [April 8, 2023, 3:19am UTC](https://discourse.julialang.org/t/retrieving-an-instance-of-an-enum-using-a-string/61183/7 "2023-04-08T03:19:50Z")

</div>

```julia
@enum LogLevel begin
    LL_INFO
    LL_DEBUG
end

```

Please also note from

```julia
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 :

```julia
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](https://discourse.julialang.org/t/solving-the-drawbacks-of-enum/74506)

---

_[View the full topic](https://discourse.julialang.org/t/retrieving-an-instance-of-an-enum-using-a-string/61183)._
