Allow functions to ignore unsupported keyword arguments

Is there a good way to let a function ignore unsupported keyword arguments?

fopts = [:kw1] opts = Dict(:kw1=>:symb1, :kw2=>:symb2) function f(; kw1 = :symb) return kw1 end 

f(;opts...) will throw METHOD ERROR

I could wrap this with 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 

I missed the path around this. It’s not that fussing if there is a penalty for execution, because I believe that they might need some kind of look. Is there a good way to poll what kwargs f accepts programmatically?

+7
julia-lang
source share
2 answers

Is this what you want?

 function g(; kw1 = :a, kw2 = :b, _whatever...) return (kw1, kw2) end 

Now it works as follows:

 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) 
+8
source share

Based on the comments of @tim and @Gnimuc, these two functions could be defined:

 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

0
source share

All Articles