Dictionary with keywargs not working

Hello!
I have been struggling with a small issue when I pass a dictionary to a function with the keywargs values assigned.
Here is minimum reproducible example:

function mySimpleFun(;
	T::Integer,	δ::Float64, σ::Float64, α::Float64
)
	sum = T + δ + σ + α
	return sum
end

attempt = Dict(
	:T => 200,
	:δ => 0.1,
	:σ => 0.2,
	:α => 0.4
)

mySimpleFun(; attempt)

I always get: ERROR: UndefVarError: T not defined
In Pluto.jl, the message is different but similar: UndefKeywordError: keyword argument 'T' not assigned.

Am I doing something wrong?
It would be very convenient to pass the same parameters to different models (defined as functions).

Thank you!

Try to call your function using splatting: mySimpleFun(; attempt...).

1 Like

Thank you! It worked. Can you please give me a glimpse into why did it work?

For now, please take a look here. (it seems up to date enough)

I’ll get back when I get some time and discuss the Dict usage specifically. But the above material should help anyway.

1 Like

Calling mySimpleFun(; attempt) would work for a function that had a single keyword arg named attempt. The function you wrote expects 4 kwargs called T, delta, sigma, and alpha. When you “splat” with ..., that’s essentially unpacking your dictionary into its 4 constituent key => value pairs.

For the most part, Julia tries to avoid DWIM, so if you pass a single object when 4 were expected, you’ll get an error.

3 Likes