Function keyword argument packing and unpacking

#1

Current behavior is this:

julia> f(;kwargs...) = kwargs
f (generic function with 1 method)

julia> f(a=1, b=2)
pairs(::NamedTuple) with 2 entries:
  :a => 1
  :b => 2

julia> f(f(a=1, b=2)...)
ERROR: MethodError: no method matching f(::Pair{Symbol,Int64}, ::Pair{Symbol,Int64})
Stacktrace:
 [1] top-level scope at none:0

Shouldn’t this be true?

f(f(a=1, b=2)...) == f(a=1, b=2)

This would allow things such as calls to a function is more dynamic ways than just passing an unpacked tuple or vector. Such as below:

julia> d = Dict(:a => 1, :b => 2)
Dict{Symbol,Int64} with 2 entries:
  :a => 1
  :b => 2

Dict(f(d...)) == d

I apologize ahead of time for lack of good writing style. I have done about 3 forum posts in my life.

0 Likes

#2

You’re very close, but you need to explicitly pass the pairs as keyword arguments, like so:

julia> f(;f(a = 1, b=2)...)
pairs(::NamedTuple) with 2 entries:
  :a => 1
  :b => 2

Otherwise your arguments are interpreted as a sequence of positional (not keyword) arguments.

2 Likes

#3

Doh! why didn’t I think of that before I posted this? Thank you very much! I guess that classifies this post as a “usage” post…

0 Likes