Idiomatic way of writing function with all named arguments and no defaults

There are a few very similar threads but often old(ish) so I’ll add another one. What’s the idiomatic way of writing something like this:

function myfun(; x = nothing, y = nothing, z = nothing)
    @assert !isnothing(x) || !isnothing(y) || !isnothing(z)

    x + y + z
end

where I want all arguments to be named at callsite (as it’s easy to mix things up and get silently wrong results) but not have defaults (as again it’s easy to go wrong by forgetting about them).


julia> function myfun(; x, y, z)
           x + y + z
       end
myfun (generic function with 1 method)

julia> myfun()
ERROR: UndefKeywordError: keyword argument `x` not assigned

work?

5 Likes

Pretty obvious, thanks!

Do I need to worry about performance with this approach given the function is called through all kwargs?

I’m not aware of any known (or common) performance holes with kwargs, but maybe it’s possible someone is able to cook up some obscure exceptions. I predict the main challenge you’ll face with this kind of API is that the error messages will tend to be worse and less helpful since they don’t always thread through the kwcall gracefully

1 Like

::Type{} arguments end up as type-unstable ::DataType fields in a NamedTuple argument to the lowered underlying function, otherwise it does as well as with positional arguments. Similar downside happens for closures capturing variables assigned to types.

Three parameters, none of which have a default?

indeed, as the OP specified