I forgot to mention one more thing: Your method is “simple” to you because your functions don’t have optional arguments. Is that right? My functions very often have optional arguments, where you can omit some of the arguments. To adopt your catch-all NamedTuple
method, you would have to write a more complicated wrapper:
# -- in one module
function f(; x = "hello", y = 3.14, z = nothing)
@show x, y, z
end
# The simple version doesn't allow for optional arguments:
# f(nt::NamedTuple) = f(; nt.x, nt.y, nt.z)
# We need the following to allow for optional arguments:
function f(nt::NamedTuple)
args = ()
if haskey(nt, :x)
args = (; x = nt.x,)
end
if haskey(nt, :y)
args = (; args..., y = nt.y)
end
if haskey(nt, :z)
args = (; args..., z = nt.z)
end
f(; args...) # Typo fixed (30 min after the posting)
end
#function g(; x = "hello", y = 3.14, z = nothing)
# @show x, y, z
#end
read_data() = (x = "x", z = "z", y = "y")
# -- in the main program
vars = read_data()
nt1 = vars[(:x,:z)] # Omit :y .
nt2 = (; vars[(:x,:z)]..., y = "replaced")
f(nt1) # works
f(nt2) # works
f(; x = "x") # I sometimes call the original interface.
In the first call, you omit “y” because you want to let the function use its own default value. The 3rd call is to the original interface.
If I write the complicated f(nt::NamedTuple)
version, then I’d also include the check in the f(nt::NamedTuple)
to detect misspelt or extraneous arguments. Then, the f(nt::NamedTuple)
would become as robust as I want.
If you want more robust control, I suggest writing function methods for custom composite types instead of NamedTuple or kwargs....
Sorry I don’t understand your point. I don’t think my method as I have shown earlier needs more improvements: I just maintain the strict interface without introducing the catch-all NamedTuple
on the function side. To manage the variables to be sent to the function, I manipulate the NamedTuple
on the caller’s side. What benefits would I get if I introduced a NamedTuple
interface to my function f
?
But, I guess this is because I don’t understand what you are proposing.