Sometimes I would find it useful to have access to the default values of keyword arguments of a function.
I wrote this macro to achieve this for functions that I defined myself:
julia> macro kwvalues(func)
@eval $func
ftype = :(typeof($(func.args[1].args[1])))
if length(func.args[1].args) == 1
@eval defaultkwvalues(::$ftype) = NamedTuple()
elseif typeof(func.args[1].args[2]) == Expr &&
func.args[1].args[2].head == :parameters
kw = func.args[1].args[2].args
keys = [typeof(k.args[1]) == Symbol ? k.args[1] : k.args[1].args[1] for k in kw]
vals = [k.args[2] for k in kw]
if length(func.args[1].args) > 2
@eval defaultkwvalues(::$ftype, $(func.args[1].args[3:end]...)) = NamedTuple
{($keys...,)}(($vals...,))
else
@eval defaultkwvalues(::$ftype) = NamedTuple{($keys...,)}(($vals...,))
end
else
@eval defaultkwvalues(::$ftype, $(func.args[1].args[2:end]...)) = NamedTuple()
end
end
julia> @kwvalues f3(x; a = 2, b = 3) = 1
defaultkwvalues (generic function with 11 methods)
julia> @kwvalues f3(x::Int; c = 3) = 1
defaultkwvalues (generic function with 11 methods)
julia> defaultkwvalues(f3, 1.)
(a = 2, b = 3)
julia> defaultkwvalues(f3, 1)
(c = 3,)
I’m sure there are nicer ways to write the macro (any suggestions are welcome ) , but is there maybe even a way to achieve the same without a macro?