Check if keyword arguments exist in Julia

I have a function to collect additional keyword arguments using ..., so this is similar to function f(args=0; kwargs...). I want to check if a keyword argument exists, say, ain kwargs.

What I'm doing is probably not elegant, first I create Dictto store keywords and corresponding values kwargs_dict=[key=>value for (key, value) in kwargs], then I use haskey(kwargs_dict, :a)to check if the akey is in the dict. Then I get its value on 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 a better way to check if the keyword argument is ain kwargsand get the value of the existed keyword argument.

+4
2

- . ( a.k.a). , , . nothing . , :

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

:

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

1- - kwargs, , , . ( ).

+4

kwargs Dict, kwargs. :

kwargs_dict = Dict(kwargs)
+6

Source: https://habr.com/ru/post/1627043/


All Articles