How do I turn a string into a specific enum type in a macro?

Viewed 580

I have a module with an enum defined in it.

module myModule
  @enum  type A B B C D

end

type1 = myModule.A

Now I want to declare an instance of this enum type but I only have a string specifying which type it is. I tried the following:

str = "B"
type2 = eval(:(myModule.Symbol($str)))

But I get a warning message which I do not quite understand:

WARNING: replacing module myModule.

and the type of type2 is also just a Symbol.

1 Answers

Probably the simplest way is to use getproperty:

julia> module myModule
           @enum type A B C D
       end
Main.myModule

julia> str = "B";

julia> getproperty(myModule, Symbol(str))
B::type = 1

Alternatively, you could create your expression as a string and then parse and evaluate it:

julia> eval(Meta.parse(string("myModule.", str)))
B::type = 1

Or, the same thing, but with string interpolation instead of using the string function:

julia> eval(Meta.parse("myModule.$str"))
B::type = 1

Note that the syntax myModule.Symbol(str) is not equivalent to myModule.B. It looks like that syntax really just calls Symbol(str) in the global scope. For example, try the following:

julia> myModule.length([1, 2, 3])
3

julia> @code_lowered myModule.length([1, 2, 3])
CodeInfo(
1 ─ %1 = (Base.arraylen)(a)
└──      return %1
)
Related