Stuart
Stuart

Reputation: 1492

Get names of keywords for Julia methods

I have a function like

function f(a = 1; first = 5, second = "asdf")
    return a
end

Is there any way to programatically return a vector with the names of the keyword arguments. Something like:

kwargs(f)
# returns [:first, :second]

I realise that this might be complicated by having multiple methods for a functionname. But I was hoping this would still be possible if the exact method is specified. For instance:

kwargs(methods(f).ms[1])
# returns [:first, :second]

Upvotes: 8

Views: 599

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42224

Just use Base.kwarg_decl()

julia> Base.kwarg_decl.(methods(f))
2-element Vector{Vector{Symbol}}:
 []
 [:first, :second]

If you need the first parameter a as well you could also try:

julia> Base.method_argnames.(methods(f))
2-element Vector{Vector{Symbol}}:
 [Symbol("#self#")]
 [Symbol("#self#"), :a]

Upvotes: 9

Related Questions