You could make it look a bit more aesthetic by defining a getproperty method that gives you slightly nicer my_dict.dataFolder syntax instead of my_dict["dataFolder"].
Some limitations of that approach:
- you need
my_dictto be a type that you’ve defined yourself otherwise defining a
is definitely type piracy since you own neitherBase.getproperty(d::Dict, s::Symbol) = ...Dict,Symbol, norgetproperty. So you’d need to wrapDictin your own type:struct MyDict dict::Dict end Base.getproperty(d::MyDict, s::Symbol) = getfield(d, :dict)[string(s)] - The keys of the
Dictmust be valid Julia identifiers, so no dashes, spaces, etc.
You can make values stored in my_dict into variables if you use eval:
mod = Module()
for (k, v) in my_dict
Core.eval(mod, :($(Symbol(k)) = $v))
end
@assert mod.dataFolder == "my_data"
But as @jling mentioned above, generally this is not what you should be doing, and in this example doesn’t actually provide any benefit over the getproperty approach. It has it’s place at times, but those are pretty limited, and really a last resort.
Another way may be with keyword arguments like:
julia> function use_variables(;
tile_size = error("tile_size not provided"),
dataFolder = error("dataFolder not provided"),
dims = error("dims not provided"),
kws... # ignore anything else.
)
@show tile_size dataFolder dims # use as variables inside function.
# ...
end
julia> use_variables(; (Symbol(k)=>v for (k,v) in my_dict)...)
tile_size = [100, 200]
dataFolder = "my_data"
dims = 20
20
Which might work if you only need a predefined set of variables to be handled.