Skip to content

Instantly share code, notes, and snippets.

@anthony-wang
Forked from tshort/julia_type.md
Created May 19, 2018 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthony-wang/952059ce0c79ba2f1f8bcce2d4fc28d5 to your computer and use it in GitHub Desktop.
Save anthony-wang/952059ce0c79ba2f1f8bcce2d4fc28d5 to your computer and use it in GitHub Desktop.
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