How to generate variables and assign values from a dictionary by metapgramming?

I am using ArgParse.jl to parse command line arguments. It returns a dictionary. But I would prefer to generate variables so it’s easier to use them. I tried to use Meta programming as follows

function main()
    parsed_args = parse_commandline()

    # Turn the dictionary into variables
    for key in keys(parsed_args)
        ex = Meta.parse("const $key = parsed_args[\"$key\"]")
    do_something(n1, n2, d1, d2)

But I got

ERROR: LoadError: UndefVarError: parsed_args not defined

What did I do wrong?

eval evaluates in global scope. parsed_args is in local scope.

@kristoffer.carlsson Anyway to fix this?

You probably want eval(:(const $(Symbol(key)) = $(parsed_args[key]))). (Note that I’m inserting the value of parsed_args[key] directly into the expression tree.) In general, it is vastly more flexible and reliable to build expression trees directly rather than parsing strings.


Yes, interpolate the values into the expression.

1 Like