7

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 
2
  • 6
    I think you want parse("a=2") (it will convert to Symbol or Expr depending on the contents of the string) Commented Dec 22, 2016 at 6:06
  • Thank you. It's what I need. I skimmed the docs (docs.julialang.org/en/release-0.5/manual/metaprogramming) at the middle for Expr but missed to check that parse is right at the top section of the page. Commented Dec 22, 2016 at 12:47

3 Answers 3

14

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Finally a useful one :)
2

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 

Comments

0

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 

3 Comments

Please share your code when answering a question with the output so people can reproduce it.
what about eval(Meta.parse("a = 2")) ?
The reply of @MarkusHauschel should be the accepted answer. It worked, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.