Phuoc
Phuoc

Reputation: 1103

How to eval string/convert string to Expr

Is there a method to convert a string to Expr? I tried the following but it doesn't work:

julia> convert(Expr, "a=2")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Expr
This may have arisen from a call to the constructor Expr(...),
since type constructors fall back to convert methods.

julia> Expr("a=2")
ERROR: TypeError: Expr: expected Symbol, got String
 in Expr(::Any) at ./boot.jl:279

Upvotes: 7

Views: 5372

Answers (3)

Braham Snyder
Braham Snyder

Reputation: 581

parse doesn't work here anymore. Now you need Meta.parse:

eval(Meta.parse("a = 2"))

(As pointed out by Markus Hauschel in a comment.)

Upvotes: 14

Alec Hoyland
Alec Hoyland

Reputation: 127

Note that as of Julia 1.0, this no longer works. Generally if you want to be evaluating string expression in Julia 1.0 you should be using expressions all the way through, e.g. :(a=2)

julia> parse("a=2")
ERROR: MethodError: no method matching parse(::Expr)

julia> @show eval(:(a=2))
eval($(Expr(:quote, :(a = 2)))) = 2
2

Upvotes: 0

Felipe Jiménez
Felipe Jiménez

Reputation: 505

As Colin said, to convert to Expr (or Symbol) you use parse. And then to evaluate the resulting Expr you use eval. Both together:

julia> eval(parse("a = 2"))
2

Upvotes: 2

Related Questions