Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 285
Stuart Avatar asked Jul 20 '21 23:07

Stuart


People also ask

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

Does Julia have methods?

Method TablesEvery function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table.

What does the splat operator do Julia?

The "splat" operator, ... , represents a sequence of arguments. ... can be used in function definitions, to indicate that the function accepts an arbitrary number of arguments. ... can also be used to apply a function to a sequence of arguments.


1 Answers

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]
like image 67
Przemyslaw Szufel Avatar answered Oct 13 '22 04:10

Przemyslaw Szufel