Getting the closest method or dispatching method with parameter types without calling

Hi,

julia> f(x::Int,y::Float64) = x*y
f (generic function with 1 method)

julia> f(x::Float64,y::Int) = x/y
f (generic function with 2 methods)

julia> f(x::Float64,y::Float64) = x+y
f (generic function with 3 methods)

julia> f(1,1)
ERROR: MethodError: no method matching f(::Int64, ::Int64)
Closest candidates are:
  f(::Float64, ::Int64) at none:1
  f(::Int64, ::Float64) at none:1
Stacktrace:
 [1] top-level scope at none:0

I want to do something like this
methods = get_closest_method(f,typeof(1),typeof(1))

methods will have the correct dispatch or the closest methods for dispatch. Or an object reporting disagreeing parameter types.

Thanks

If you’re getting a method error, that means there is no unique closest method. Are you asking about how to use reflection or just trying to make the method error go away?

I am able to dispatch to a fallback function f(args…;kwargs…)
However I would like to get my closest candidate(s) among the methods in the fallback method using reflection or any programmatic way. The ones shown in the method error are the closest I assume.
What I would like is also which parameters didn’t match as well in type.

Thanks

The closest method list is very much a heuristic and shouldn’t be relied on for anything in your code.

1 Like

I assume there is a way to sort the methods according to number of parameters didn’t type match
and report those non-matching types in each candidate.

right?

Not easily. You would have to look at the existing code for the closest method list and modify it.

Can you point me to that code please?
Thanks

Is it possible to take action regarding dispatch taking that method error in account using reflection?
What were you going to suggest?

Thanks

I would suggest implementing the missing method rather than trying to guess.

3 Likes

Is there an example where someone uses method error and makes a dispatch with that info?

Thanks

Not that I can think of. What’s the issue with just defining the method?

3 Likes

Don’t try to fight the system, join it :smile:. Those ambiguity errors are there for good reason, and the way to stop them is to write code that doesn’t have them. If you’re getting them all the time, you may be doing something else wrong, like declaring types in places you shouldn’t, etc. There’s a whole section in the manual that may help, see https://docs.julialang.org/en/latest/manual/methods/#man-method-design-ambiguities-1.

3 Likes