Julia:是否可以将参数字典传递给函数?

A P*_*oor 4 types arguments metaprogramming keyword-argument julia

我有一个函数参数字典,我想传递给一个函数。例如:

function test_function(foo::Int, bar::String)
    #...
end

params = Dict(
    "foo" => 1,
    "bar" => "baz"
)
Run Code Online (Sandbox Code Playgroud)

在 Python 中,我可以像这样将所有参数作为 kwargs 传递:

function test_function(foo::Int, bar::String)
    #...
end

params = Dict(
    "foo" => 1,
    "bar" => "baz"
)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试时params...,我收到以下错误:

julia> test_function(params...)
ERROR: MethodError: no method matching test_function(::Pair{String,Any}, ::Pair{String,Any})

Run Code Online (Sandbox Code Playgroud)

有没有办法在 Julia 中做类似的事情?

Cam*_*nek 7

Julia 明确区分了位置参数和关键字参数。为了澄清区别,您可以使用分号将位置参数与关键字参数分开。您可以使用 将对象解包为位置参数或关键字参数...,这称为splatting 运算符

如果要将对象解包为关键字参数,则它需要是成对或元组的迭代器。如果将对象解包为位置参数,解包的元素类型需要匹配函数的方法之一。

下面是一个例子:

function foo(x, y; a=1, b=2)
    x + y + a + b
end

t = (1, 2)
d = Dict(:a => 3, :b => 4)
Run Code Online (Sandbox Code Playgroud)
julia> foo(t... ; d...) 
10
Run Code Online (Sandbox Code Playgroud)

但是,请注意字典中的键(或成对/元组的迭代器)必须是符号,以便解包为关键字参数才能工作:

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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅手册的可变参数关键字参数部分。