How to collect keyword arguments in a Dict?


#1

How can I get the keyword arguments and their default values of a function in a dict in Julia?

E.g:

function foo(x; a = 1, b = 2, c= 3)
  # How do I get a dict of keyword arguments: Dict(a=>1, b=>2,c=3) ??,
  # so I can pass this Dict easily to another generic function taking v 
  # variable keyword arguments for further processing
end

#2
function foo(; args...)
    Dict(args)
end

#3

I know how to do that. But I want to be able to do it for a function where the keyword arguments are explicitely defined in the function/method definition, like in the example.
Any thoughts? Thanks.


#4

Note that cross-posting with StackOverflow is discouraged - if you do it it’s nice to provide the link: https://stackoverflow.com/questions/46948486/collect-function-keyword-arguments-in-dict-in-julia
Also, “I know how to do that” easily comes across as impolite.


#5

Anyway, if you want to do that, the easiest way is to define the Dict first, like in the answer given on SO:

args = Dict(:a => 3, :b => 4)
foo(;args...)

Passing keyword arguments through a thin wrapper without explicitly writing them out
#6

Thanks. I didn’t want to come across a impolite.
Anyway, I had thought of that, but it wouldn’t work for what I want to do (I think), which is to define a function with default values for the keyword arguments, but that function also has one keyword argument that either contains ‘nothing’ or a Dict with a subset of the keyword arguments of that function. The value of any keyword arguments that are keys in the Dict will be replaced by the corresponding values in the Dict. That way is easy to write a general function that has a lot of keyword arguments with specific defaults, but where subsets of those can be easily changes by passing a Dict (for example, which comes in handy when testing different models with varying parameters sets).
Any thoughts on how to go about this in perhaps another way? (I used this method in Python by getting the passed arguments by creating a copy of the locals() just after entering the function, so I was hoping to do something similar in Julia). Many thanks for any advice.


#7

If you have lots of keywords arguments, consider defining a struct to contain them. To change a subset of them, see the nice keyword constructor syntax of


or the packages mentioned there.


#8

Thanks.