Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow function to ignore unsupported keyword arguments

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?

like image 705
Alexander Morley Avatar asked Mar 03 '17 12:03

Alexander Morley


People also ask

How do you ignore a keyword in Python?

Use a try/except block to ignore a KeyError exception in Python. The except block is only going to run if a KeyError exception was raised in the try block. You can use the pass keyword to ignore the exception.

Can non-keyword arguments be passed after keyword arguments?

Yes, Python enforces an order on arguments: all non-keyword arguments must go first, followed by any keyword arguments.

Does Python support keyword argument in function?

The current Python function-calling paradigm allows arguments to be specified either by position or by keyword. An argument can be filled in either explicitly by name, or implicitly by position. There are often cases where it is desirable for a function to take a variable number of arguments.

What are non-keyword arguments?

When a function is invoked, all formal (required and default) arguments are assigned to their corresponding local variables as given in the function declaration. The remaining non-keyword variable arguments are inserted in order into a tuple for access.


1 Answers

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)
like image 161
avysk Avatar answered Oct 21 '22 12:10

avysk