5
votes

I have a function collect extra keyword arguments using ..., so it is like function f(args=0; kwargs...). I want to check if a keyword argument, let' say, a, exists in kwargs.

What I do probably is not an elegant way, I first create a Dict to store the keywords and corresponding values kwargs_dict=[key=>value for (key, value) in kwargs], then I use haskey(kwargs_dict, :a) to check if a is a key in the dict. Then I get its value by kwargs_dict[:a].

function f(; kwargs...)
   kwargs_dict = [key=>value for (key, value) in kwargs]
   haskey(kwargs_dict, :a)
   a_value = kwargs_dict[:a]
end

f(args=0, a=2)
> true

f(args=0)
> false

I wonder if there is better way to check if the keyword argument a is in kwargs and to get the value of the existed keyword argument.

2

2 Answers

7
votes

You can just pass kwargs to the Dict constructor to get a dictionary representation of the kwargs. For example:

kwargs_dict = Dict(kwargs)
4
votes

Another method is to use default values for named keyword variables. With the default being a special value (a.k.a sentinel value). When a value is supplied by the user it overrides the default and this can easily be checked. nothing is a commonly used value. Specifically, for the example in the question:

julia> function g(; a = nothing, kwargs...)
    kwargs_dict = [key=>value for (key, value) in kwargs]
    a != nothing
end
g (generic function with 1 method)

Gives the functionality:

julia> g(args=0, a=2)
true
julia> g(args=0)
false

The advantage is 1st speed - default valued keyword arguments can avoid the kwargs dictionary and if possible optimization will drop the whole dictionary setup code. The 2nd advantage could be readability (but to each his own taste).