Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert a string to a Julia type

This is code to convert a string to a type based on discussions here:

https://groups.google.com/d/msg/julia-dev/q9lG55PMdlc/C3IRKbKXcpoJ

type UnsupportedType
end

is_valid_type_ex(s::Symbol) = true
is_valid_type_ex(x::Int) = true
is_valid_type_ex(e::Expr) = (e.head == :curly || e.head == :tuple) && all(map(is_valid_type_ex, e.args))


function julia_type(s::String)
    e = parse(s)[1]
    typ = UnsupportedType
    if is_valid_type_ex(e)
        try     # try needed to catch undefined symbols
            typ = eval(e)
            if !isa(typ, Type)
                typ = UnsupportedType
            end
        catch
            typ = UnsupportedType
        end
    else
        typ = UnsupportedType
    end
    typ
end

Examples:

julia> julia_type("Int")
Int64

julia> julia_type("Array{Array{Int64,1},1}")
Array{Array{Int64,1},1}

julia> julia_type("Dict{(Symbol,Array{Int64,1}),Array{Array{Int64,1},1}}")
Dict{(Symbol,Array{Int64,1}),Array{Array{Int64,1},1}}

julia> julia_type("Dict")
Dict{K,V}

julia> julia_type("asdf")
UnsupportedType

julia> julia_type("run(`ls`)")
UnsupportedType

julia> julia_type("sin(3)")
UnsupportedType

julia> julia_type("Any")
Any

julia> julia_type("Something that shouldn't parse")
UnsupportedType

Notes:

  • This uses eval, and that can be dangerous. Hopefully, is_valid_type_ex() is strict enough to avoid issues.

  • Unions are not supported. That should probably be uncommon for concrete types stored to a file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment