7

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?

3
  • You could define your function as f(x; kwargs...) = (kwargs = Dict(kwargs); ...) and just use the keywords your function should support and ignore the rest.
    – tim
    Mar 3, 2017 at 12:33
  • if i understood properly, you might look for something like this: fopts=methods(methods(f).mt.kwsorter).mt.defs.func.lambda_template.slotnames. i guess there must be a clean way to do this.
    – Gnimuc
    Mar 3, 2017 at 12:56
  • Indeed I feel like there are other usecases for a getkwargs function... Mar 3, 2017 at 13:22

2 Answers 2

8

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)
0
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.