I have a dictionary of function arguments that I want to pass to a function. For example:
function test_function(foo::Int, bar::String)
#...
end
params = Dict(
"foo" => 1,
"bar" => "baz"
)
In Python, I could pass all parameters as kwargs like this:
def test_function(foo: int, bar: str):
#...
params = {
"foo": 1
"bar": "baz"
}
test_function(**params)
But when I try params...
, I get the following error:
julia> test_function(params...)
ERROR: MethodError: no method matching test_function(::Pair{String,Any}, ::Pair{String,Any})
Is there a way to do anything similar in Julia?
Julia makes a clear distinction between positional arguments and keyword arguments. To clarify the distinction, you can separate positional arguments from keyword arguments with a semicolon. You can unpack objects into positional arguments or keyword arguments using ...
, which is referred to as the splatting operator.
If you want to unpack an object into keyword arguments, it needs to be an iterator of pairs or tuples. If you unpack an object into positional arguments, the unpacked element types need to match one of the methods of the function.
Here's an example:
function foo(x, y; a=1, b=2)
x + y + a + b
end
t = (1, 2)
d = Dict(:a => 3, :b => 4)
julia> foo(t... ; d...)
10
However, note that the keys in the dictionary (or iterator of pairs/tuples) must be symbols in order for unpacking into keyword arguments to work:
julia> e = Dict("a" => 3, "b" => 4);
julia> foo(t... ; e...)
ERROR: MethodError: Cannot `convert` an object of type String
to an object of type Symbol
For more info, see the Varargs and Keyword Arguments sections of the manual.