How to call a function with a keyword argument whose name is stored in a variable

If someone need it… or for myself when I will forget it :wink:

This snippet allows to call a function with a keyword argument whose name is stored in a variable:

foo(x;extra=0) = x+extra
keyword = "extra"
foo(2,extra=1)
foo(2;(Dict(Symbol(keyword)=>1))...)

You can skip the NamedTuple(Dict(.... Tuples and vectors of pairs will work:

foo(x; extra=0) = x + extra
keyword = "extra"
foo(2; extra=1)
foo(2; (Symbol(keyword)=>1,)...) # Note the comma!
foo(2; [Symbol(keyword)=>1]...)

I’d assume any iterable of pairs would work.

Making a single element collection just to splat it is redundant. It’s fine to go directly with the Pair:

foo(2; Symbol(keyword) => 1)
2 Likes

Attention to a subtle particular… at calling time you need also to be specific with using the semicolon. This is not true when using the keyword argument directly, e.g. these both work:

foo(2,extra=1)
foo(2;extra=1)

But this doesn’t:

foo(2, Symbol(keyword) => 1) # error