A good way of checking whether a keyword argument is present

Hello,

I`d like to check for a presence of a particular keyword argument. I wanted to cross-check whether I am doing the right thing here.

This works but I feel using “filter” is perhaps an overkill and there might be a simpler way of achieving this.

function testKwargs(; kwargs...)
    # looking for keyword argument "width"
    width = isempty(filter(x->x.first==:width, kwargs)) ? 0 : kwargs[:width] 
end

testKwargs(; width=8, style="solid") # <--- gives 8
testKwargs(; widthh=8, style="solid") # <--- gives 0 (mind the misspelled "widthh")
function testKwargs(; kwargs...)
    # looking for keyword argument "width"
    get(kwargs, :width, 0)
end

Is that ok?

3 Likes

Absolutely! Thanks, this is neat!

@guoyongzhi gave the right answer for the actual problem, but to answer the question in the title, you can check for presence of a keyword like this:

if :width in keys(kwargs)
    ...
2 Likes

Actually I wonder if you shouldn’t rather do this:

function testKwargs(; width=0, kwargs...)
    ...
3 Likes

@sudete thanks for your additional thoughts. You are right about setting the default value in the function signature. Thanks!

1 Like

Also note that signatures like

function testkwargs(; kwargs...)
    ...

will accept arbitrary keyword arguments. That may not be desired, since mistyping a keyword arg could silently fail, as you noted (i.e. the function would accept it, but fail to alert the user that the kwarg was incorrect, and the kwarg would not act as the user intended).

That behavior might be necessary for functions which might pass on kwargs to callbacks, etc., but the common way to define optional kwargs is to set the default value for the keyword arg to nothing, and then check for it in the function body:

function testkwargs(; width=nothing)
    if !isnothing(width)
        ...
4 Likes

@halleysfifthinc thanks for sharing this perspective. Indeed, unless functions pass on kwargs to callbacks etc. it is a good practice to set each kwarg to nothing to enable dispatching mechanism to check on each associated keyword. The code quality goes up, I like that :slight_smile: .