Updating of named tuple defaults in Julia

Following the advice about appropriate data structures, I’ve changed a model I’m working on to contain its parameters in a named tuple (in a separate params.jl file) created with the @with_kw macro, like so:
defaults = @with_kw (paramone = 1, paramtwo = 2)

The model functions call these parameter along these lines:
foo(argone, argtwo, parameters=defaults())
@unpack paramone, paramtwo = parameters
result = argone * paramone + argtwo * paramtwo
return result
end

While I can pass specific parameters to the function, I may wish to adjust the defaults instead. Unfortunately, I’m running into problems with this. I understand that named tuples are immutable and I suppose the issue is with redefining them. I do load Revise.jl in my startup.jl, but it throws an error :

Error: evaluation error │ mod = MyModule.Params. │ ex = :(default = #= /PARAMSFILEl:4 =# @with_kw((paramone = 1, paramtwo = 2) exception = │ UndefVarError: ##NamedTuple_kw#364 not defined │ Stacktrace: [...]

Does this imply that I need to re-load the whole module when I change the defaults or is there a way to help Revise to do its thing?

I have never had any issues with Revise and named parameters @with_kw. It all worked great for me. But I have never used that exact pattern, calling the @with_kw generated function within the arguments themselves.

Usually my pattern instead has been to require the parameters to be passed in and have the defaulting behavior done prior to the call to foo.

Maybe see if that works first, i.e.

foo(argone, argtwo, parameters)
    @unpack paramone, paramtwo = parameters
    return argone * paramone + argtwo * paramtwo
end
p = defaults()
foo(argone, argtwo, p)

and if that doesn’t cause you any trouble with Revise, then perhaps it is a Revise bug in the current version?

Another option is to check whether it has anything to do with the @with_kw or if it might in fact just be Revise with the pattern of calling a function for defaults. i.e. something like

defaults() = (paramone = 1, paramtwo = 2)

foo(argone, argtwo, parameters=defaults())
@unpack paramone, paramtwo = parameters
result = argone * paramone + argtwo * paramtwo
return result
end

If that fails, then it isn’t a @with_kw and Revise compatibility issue, but something more central to how Revise works.

1 Like

Many thanks, very useful advice! The values don’t seem to update in either case, so it should either be a fundamental Revise issue or some mistake in my code. In any case, the first pattern is cleaner code in that it separates the functions from the parameters, so I’ve implemented it with good effect.

1 Like