Metaprogramming: Splatting of key word arguments

In the docs there is this example of metaprogramming:

julia> args = [:x, :y, :z];

julia> :(f(1, $(args...)))
:(f(1, x, y, z))

Now i would like to do the same for keyword arguments:

julia> kwargs = [:(x=nothing), :(y=nothing), :(z=nothing)];

julia> :(f(1; $(kwargs...)))
:(f(1; $(Expr(:(=), :x, :nothing)), $(Expr(:(=), :y, :nothing)), $(Expr(:(=), :z, :nothing))))

Which is not what I expected.
Is there any way to do this? I tried splatting a Dict instead. But it also didn’t work.

Keyword arguments are written with =, but they actually get parsed as a special kind of expression whose head is :kw not :=. You can see this with dump:

julia> dump(:(f(;x = 1)))
Expr
  head: Symbol call
  args: Array{Any}((2,))
    1: Symbol f
    2: Expr
      head: Symbol parameters
      args: Array{Any}((1,))
        1: Expr
          head: Symbol kw
          args: Array{Any}((2,))
            1: Symbol x
            2: Int64 1

So I can make your example work by doing:

julia> kwargs = [Expr(:kw, :x, :nothing), Expr(:kw, :y, :nothing), Expr(:kw, :z, :nothing)];

julia> :(f(1; $(kwargs...)))
:(f(1; x = nothing, y = nothing, z = nothing))
1 Like