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.
A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .
an exclamation mark is a prefix operator for logical negation ("not") a! function names that end with an exclamation mark modify one or more of their arguments by convention.
Method TablesEvery function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table.
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword. A. A.
You can just pass kwargs
to the Dict
constructor to get a dictionary representation of the kwargs. For example:
kwargs_dict = Dict(kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With