Evaluate string based on dictionary values


Is possible to evaluate a string something like “x + y” or “x > y” based on values of x and y taken from dictionary?
In python works if I write eval(“x+y”, dict), but in julia I can’t do it.

Thank you!

Yes, it’s possible. But what problem are you trying to solve here? Why are you passing expressions as strings rather than as functions?

I need this for evaluation of some expressions from text file.
The text file content is something like this:

Parameters: a, b, c
If a+b >c {
Print “ok”

I managed to write an if, while and for parser but I don’t know how to parse the a+b>c or other expression, so i need to use julia parser and eval but with values from dictionaries.

So, you are defining a custom input language? Why not have the input language be Julia, possibly with macros to add domain-specific syntax if needed?

Well, this is the problem… I don’t want to define in julia program x and y, I want to evaluate an expression with x and y defined in dictionary. The values from dictionary will be introduced from readline() in console.

@stevengj yes this is a pseudolanguage for data aquisition using serial, usb and gpib protocol.

1 Like

If you want to define local variables from a dictionary, you can do:

function parse_eval_dict(s::AbstractString, locals::Dict{Symbol})
    ex = Meta.parse(s)
    assignments = [:($sym = $val) for (sym,val) in locals]
    eval(:(let $(assignments...); $ex; end))


julia> parse_eval_dict("x + y", Dict(:x => 30, :y => 47))

But if I were you I would re-think your whole approach. Rather than defining and parsing a brand new “pseudolanguage”, it would be vastly easier, more flexible, and faster to just let users write Julia code. If you want to provide a compact domain-specific syntax you can do it with macros.

Note that if you are worried about safety/security (i.e. if the user inputs aren’t trusted), you will need to filter the Meta.parse output to allow only a small set of allowed expressions.


Ok, thank you very much! I want to write a pseudo-language for users who don’t know how to program verry well and to interact with measurement intruments. I want that most of the work to be done under the hood, and the final user only to write some intuitive lines of code. I will think about your idea! Thanks!

1 Like