Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if keyword arguments exist in Julia

Tags:

julia

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.

like image 640
Conta Avatar asked Feb 02 '16 15:02

Conta


People also ask

What is :: In Julia?

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 .

What is Julia exclamation mark?

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.

Does Julia have methods?

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.

What are keyword arguments in Python?

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.


1 Answers

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

kwargs_dict = Dict(kwargs)
like image 120
Chisholm Avatar answered Oct 17 '22 06:10

Chisholm