If I have a string such as, "Float64", can I convert it to the Julia DataType?

Basically, if I have my type written in a string format, can I convert it to the actual DataType inside of Julia?

Kind regards

julia> eval(Meta.parse("Float64"))

(But if at all possible, you should avoid passing information like this as strings. There are plenty of other ways to serialize data.)


In simple cases, you can do something like

julia> getproperty(Base, Meta.parse("Float64"))

which I think is (slightly) better than using eval. Note that this trick does not easily generalize to more complex situations (like e.g. "Vector{Int}").

That being said, I’d still stick to the advice above and avoid doing such things if possible.

1 Like

If it’s just a single symbol, you don’t even need Meta.parse — you can do getproperty(Base, Symbol("Float64")) … but needing to do this is often a sign that you should re-think what you are doing.


Thank you @ffevotte I really like this solution! Exactly what I need.

@stevengj I fully want to avoid eval it is a bit spooky to me. In my case I have a data format with a dict and some low level data types, i.e. Float64, Int32 etc. So ffevotte solution avoids eval and is perfect in this case.

Still I am quite curious, do you have an example of “needing to do this…” ? I would like to understand better :slight_smile:

EDIT: Unsure who to mark as solution :slight_smile:
EDIT2: Marked steven’s answer as solution, Meta.parse had a small bug when used inside of a for loop of a function extracting a string value from a dict, it would return Float64, but the sizeof it only as 7, so just a symbol not the type.

Kind regards

A data format in a file? Why not use one of the existing serialization formats?

A data format in memory? Then you shouldn’t need to store anything as a string (except for strings).

It’s hard to give more information without some more context about your needs.

If you just have a symbol as a string, like "Float32", it’s simplest and fastest to avoid both parse and eval as explained in If I have a string such as, "Float64", can I convert it to the Julia DataType? - #4 by stevengj

1 Like

Got it, using getproperty(Base, Symbol("Float64")).

And awesome, thanks for explaining. Will give it a go now and if starts to break, I will resort to making a dict for look up.

Kind regards

Not sure what you mean here. Meta.parse by itself will just return the symbol. You still have to call getproperty or similar to get the type.

1 Like

If the strings to be converted refer to types, you could use such a scheme

function allsubtypes(T::Type)
    isconcretetype(T) && return T
    vcat(T , [allsubtypes(sT) for sT in subtypes(T)]...)




function allsubtypes(T::Type)
    return isconcretetype(T) ? T : vcat(T , allsubtypes.(subtypes(T))...)