How does `kwargs...` pass into another function?

Hi all,

I’m trying to understand the parsing of keyword arguments in Julia functions. In the following code snippet, I created foo1() which takes in 2 keyword arguments, and bar1() which takes in keyword arguments to pass into foo1().

julia> function foo1(;a=1,b=2)
           println("$a $b")
       end
foo1 (generic function with 1 method)

julia> function bar1(;kwargs...)
           foo1(kwargs...)
       end
bar1 (generic function with 1 method)

julia> bar1()
1 2

julia> foo1(a=2)                        # No issues here
2 2

But now I’m facing issues trying to modify arguments in foo1 through bar1. How do I fix this?

Note: I’m currently using Julia v1.7.2.

julia> bar1(a=2)                # same error with bar1(;a=2)
ERROR: MethodError: no method matching foo1(::Pair{Symbol, Int64})
Closest candidates are:
  foo1(; a, b) at REPL[36]:1
Stacktrace:
 [1] bar1(; kwargs::Base.Pairs{Symbol, Int64, Tuple{Symbol}, NamedTuple{(:a,), Tuple{Int64}}})
   @ Main .\REPL[37]:2
 [2] top-level scope
   @ REPL[39]:1

Thanks in advance.

1 Like

It’s easy to miss, but you’re actually unpacking the keyword arguments into foo1 as positional arguments. You’ll need a ; in there to let Julia know that you’re unpacking into the keyword arguments:

function bar1(; kwargs...)
    foo1(; kwargs...)
end
1 Like