Rules for method dispatch with keyword arguments

The documentation here states:

Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

However, this is not precisely true as method dispatch takes into account if some method defines a keyword argument or not. Here is an example:

julia> f(x::Int) = "int"
f (generic function with 1 method)

julia> f(x; kwarg) = "any"
f (generic function with 2 methods)

julia> f(1)
"int"

julia> f(1, kwarg=nothing)
"any"

My question is if this is intended. If yes, then probably the documentation should be made more precise.

1 Like

The dispatch in your example is based on the positional argument I guess, since its untyped in the second case. What happens if you type that to Int? I think maybe it overwrites the first case.

If I type it to Int then the method is overwritten. But the point is that the second method should have a different signature in the positional parameter space. I chose Any but equally well I could have written e.g.:

f(x::Integer; kwarg) = "integer"

and the same problem would arise.

For a reference: this is not an artificial question but in DataFrames.jl we actually have methods which for “wider” (something like catch-all) method signature take keyword arguments but for narrower signatures did not take keyword arguments (because they were not needed). I initially expected that passing a keyword argument with a more specific type would throw an error (because the narrower function did not accept keyword arguments) - and this would be in line with what the documentation currently says.

1 Like

https://github.com/JuliaLang/julia/issues/9498

3 Likes

Thank you. I expected this is not new, but could not locate the relevant discussion.