One thing to note about using @eval as mentioned in Sean’s reply is that 
eval (and by extension @eval) does not evaluate expressions in a function’s 
scope, but rather in the global scope of the module.
This might have unexpected results:

julia> function f(d)
           for (k, v) in d
               @eval $k = $v
           end
       end
f (generic function with 1 method)

julia> x
ERROR: UndefVarError: x not defined

julia> f(Dict(:x => 1))

julia> x
1

You could instead use a function with keyword arguments and pass it a 
dictionary:

julia> g(; x = error("provide x"), args...) = nothing
g (generic function with 1 method)

where args... discards any variables you don’t want to handle. x could also 
be given a default value rather than throwing an error when not provided.
You’d then call it like so:

julia> g(; Dict(:x => 1, :y => 2)...)

Although it’s slightly more verbose, this way won’t result in side-effects 
caused by using eval.

— Mike
On Monday, 16 February 2015 00:17:54 UTC+2, Martin Johansson wrote:
>
> Is there a way to "assign" the values of a Dict to the corresponding keys 
> such that I get "variables" (symbols?) with names given by the keys? Let's 
> assume the keys are for example strings which would work as variables.
>
> The reason for why I would want to do this is to have functions where 
> explicit variables are used rather than Dicts, primarily for readability. 
> I'm suspecting that this is not a recommended way of doing things (since I 
> couldn't find any info along these lines when searching), and if this is 
> the case please set me straight.
>
> Regards, m
>
>
>

Reply via email to