Converting String to DataType

I’m using Julia v1.2 rc1 and I’d like to be able to convert a string to a data type but eval(Symbol("SomeComplexType")) isn’t doing it for types that are not basic. For instance this

eval(Symbol("Float64"))

returns Float64 as is expected, but it won’t work for eval(Symbol("Array{Float64}")) since this is not a single symbol. It looks as if Julia used to be able to eval more complex types (Parse String to DataType) but that method doesn’t work anymore.

Would appreciate help on this.

Thanks!

You can access julia’s parser through Meta.parse to get the correct object.

julia> eval(Meta.parse("Array{Float64}"))
Array{Float64,N} where N

However, I’d caution you that parsing and evaluating strings is in most cases not the ideal way to achieve whatever it is you’re trying to do (though there are exceptions).

If you feel like explaining why you need to parse and evaluate a string to a datatype, perhaps we can advise on a safer and more performant option.

That’s awesome thanks.

I’m writing something that can read/write any array type from/to binary files. I ran into some issues when trying to write CatgegoricalArrays to file. They have type element type CategoricalString{UInt32} which is where my code failed but your suggestion fixed it. I’m definitely open to suggestions on how to do this better.

As was mentioned in the thread you linked, if your program loads text data and blindly evals it, you open any users of your code to attacks where someone can put malicious code into the data and have it be evaluated.

I’m no expert on this sort of stuff, but have you considered using regular expressions or just a simple dictionary to match strings from the file with types? That way there’s no arbitrary evaluation of code.

2 Likes