When I want to forward kwargs from an API function to various internal dispatched methods I just allow them to have arbitrary kwargs, like so
external_api(x; kw...) = _internal(x; kw...)
_internal(x::Float64; kw1 = 1, kw...) #only needs kw1, but allows any other
_internal(x::Int; kw2 = 2, kw...) #only needs kw2, but allows any other
Is this the recommended pattern? The problem I see is that if I use a wrong keyword in the external_api, it will not complain. In other languages (e.g. Mathematica) there is a way to filter keywords allowed by a given function, so that if one uses a wrong keyword, it errors. Is there a similar pattern that one can use in Julia so that external_api(x; kw3 = 3) errors?
julia> allowed_kws = (:kw1, :kw2)
(:kw1, :kw2)
julia> function external_api(x; kws...)
for kw in keys(kws)
kw in allowed_kws || throw(KeyError(kw))
end
_internal(x, kws...)
end
external_api (generic function with 1 method)
julia> _internal(x::Float64; kw1 = 1) = x+kw1
_internal (generic function with 2 methods)
julia> _internal(x::Int64; kw2 = 1) = x*kw1
_internal (generic function with 2 methods)
julia> external_api(2, kw3=3)
ERROR: KeyError: key :kw3 not found