Reputation: 4181
Is there a nice way of allowing a function to ignore unsupported keyword arguments?
fopts = [:kw1]
opts = Dict(:kw1=>:symb1, :kw2=>:symb2)
function f(; kw1 = :symb)
return kw1
end
f(;opts...)
will throw a METHOD ERROR
I could wrap it in something like this, but then I still need to know which kwargs f
will support?
function f2(fopts; kwargs)
f(; Dict(key=>get(opts, key, 0) for key in fopts)...)
end
Am I missing a way around this. Not that fussed if there is a performance penalty as I imagine their may need to be some kind of look up. Is there a good way of interrogating what kwargs f
accepts programatically?
Upvotes: 7
Views: 1021
Reputation: 4181
Based on both @tim & @Gnimuc's comments one could define these two functions:
getkwargs(f) = methods(methods(f).mt.kwsorter).mt.defs.func.lambda_template.slotnames[4:end-4]
usesupportedkwargs2(f::Function, args...; kwargs...) = f(args...; Dict(key=>get(Dict(kwargs),key,0) for key in getkwargs(f))...)
But maybe there is a better way
Upvotes: 0
Reputation: 2035
Is this what you want?
function g(; kw1 = :a, kw2 = :b, _whatever...)
return (kw1, kw2)
end
Now it works like this:
julia> g()
(:a,:b)
julia> g(kw1 = :c)
(:c,:b)
julia> g(kw2 = :d)
(:a,:d)
julia> g(kw2 = :e, kw1 = :f, kw3 = :boo)
(:f,:e)
Upvotes: 10