Keyword Arguments

How do we get the number (and/or name) of keyword arguments of a function?

For instance,
f(;x, y, z) = x+y+z
arguments(f)

Thanks!

After some digging it looks like you want methods(f)

But the objects in that look kind of ugly and complicated. Could you explain more what you are trying to do?

Something similar to this function:

arguments_number(f) = first(methods(f)).nargs-1
f2(x, y) = x+y
arguments_number(f2) #2

But for keyword arguments

I mean, more broadly, what is the ultimate goal you wish to accomplish?

1 Like

I’m reading parameters and values from a CSV file,
However, I want to filter those that will be used by a given function.

How about hasmethod?

julia> f(;x, y, z) = x + y + z;

julia> hasmethod(f, Tuple{}, (:x, :y, :z))
true
1 Like

Ugly, but he following gives you the number of arguments of the generated kwsorter function in the methods table:

julia> methods(methods(f).mt.kwsorter).mt.max_args
3

I would look for another approach without the need for counting keyword arguments.

1 Like

Yes, that may work, although I would have to make a trial-and-error process.
I also find this, but I don’t know whether it’s very safe:

kwargs_number(f) = length(first(methods(f)).roots)-4

But shouldn’t you also know what names are available for input? I don’t quite understand why the number of keyword arguments would be important rather than which arguments in particular.

Yes, you’re right.
Here’s my final solution:

filter_kwargs(args, f) =
  if hasmethod(f, Tuple{}, args)
    args
  else filter_kwargs(args[1:end-1], f)
  end

f1(; x, y, z) = x+y+z
filter_kwargs((:x, :y, :z), f2)

Thank you so much!

1 Like