Function to set default parameters and easily update them

I am trying to understand the most Julia way to create a function that specifies some default parameters that can also be modified by inputing external parameters.

pars = default_pars() would return all the default parameters.

pars = default_pars(a=8., b=7.)would return all default parameters but would in addition set a new value for parameters a and b.

Below is a Python example of what I have in mind.

Thanks.

def default_pars(**kwargs):
  pars = {}

  pars['a'] = 1.     
  pars['b'] = 2.    
  pars['c'] = 3. 

  # external parameters if any
  pars.update(kwargs)

  return pars

What about this:

default_pars(; a=1, b=2, c=3) = (; a, b, c)

Usage example:

julia> default_pars(a=8.0, b=7.0)
(a = 8.0, b = 7.0, c = 3)

Or if you want to let the user give additional values for which you don’t have defaults:

default_pars(; kwargs...) = (a=1, b=2, c=3, kwargs...)

# Example:
default_pars(b=7.0, d=1)

# output:
(a = 1, b = 7.0, c = 3, d = 1)
2 Likes

The main way to do this is with what are called keyword arguments. There is also a package that offers addition functionality for more complicated cases: