# How to find if a method is implemented for an interface?

**URL:** <https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636>\
**Category:** General Usage\
**Created:** [November 29, 2016, 7:04pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636 "2016-11-29T19:04:36Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)\
**Post date:** [November 29, 2016, 7:04pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/1 "2016-11-29T19:04:36Z")

</div>

Suppose I have a simple interface for which some methods are optional:

```julia
abstract Foo{T}
method1{T}(::Foo{T}, x, y)
method2{T}(::Foo{T}, a, b) # optional

```

The user of the interface should implement `method1`, but the implementation of `method2` is optional.

By the time I am using the user type derived from Foo{T}, I need to know if the `method2` is available. How can I do this in Julia?

---

<div class="post-metadata">

**Author:** ![Evizero](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/evizero/32/10118_2.png) [@Evizero](https://discourse.julialang.org/u/Evizero)\
**Post date:** [November 29, 2016, 7:08pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/2 "2016-11-29T19:08:34Z")

</div>

Does `method2` have a fallback method that would be called in the case no special implementation is provided for the type? If not you could try using `method_exists`.

---

<div class="post-metadata">

**Author:** ![akis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/akis/32/156_2.png) [@akis](https://discourse.julialang.org/u/akis)\
**Post date:** [November 29, 2016, 8:39pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/3 "2016-11-29T20:39:51Z")

</div>

You may prefer the function `applicable(method2, instance, a, b)`, both functions found in [Generic Functions](http://docs.julialang.org/en/release-0.5/stdlib/base/#generic-functions).

---

<div class="post-metadata">

**Author:** ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)\
**Post date:** [November 29, 2016, 9:54pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/4 "2016-11-29T21:54:53Z")

</div>

Thank you @Evizero, this looks like a good starting point.

---

<div class="post-metadata">

**Author:** ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)\
**Post date:** [November 29, 2016, 9:55pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/5 "2016-11-29T21:55:37Z")

</div>

Thank you @akis for the addition, also very helpful.

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [November 29, 2016, 10:18pm UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/6 "2016-11-29T22:18:48Z")

</div>

`method_exists` and `applicable` may work depending on the use case. But note that checking `method_exists` happens at runtime, which may not be what you want. Here’s a more complicated but possibly more performant option (depending on whether compile-time enhancements out-weigh the cost of compilation) by mixing `method_exists` with traits.

In JuliaDiffEq, our interface for providing extra functions is [by adding additional dispatches](https://juliadiffeq.github.io/DiffEqDocs.jl/latest/features/performance_overloads.html#Other-Available-Functions-1). Because this was very important to us, we came up with a way to check for the existence of dispatches that will actually work at compile time (i.e. if you check the `@code_llvm`, the function `has_jac(f)` (checks if the Jacobian dispatch exists) will compile down to a true/false, and in codes which use `if has_jac(f)` the inappropriate branch will compile away and no checking needs to be done at runtime).

You can see the PR with how we came about the solution here:

> <https://github.com/SciML/DiffEqBase.jl/pull/2#issuecomment-261452685>
>
> I got it!
> 
> \`\`\` julia
> @traitdef HasJac{F}
> \_\_has\_jac(f) = check\_first\_arg(f, Val{:…jac})
> @generated SimpleTraits.trait{F}(::Type{HasJac{F}}) = \_\_has\_jac(F) ? :(HasJac{F}) : :(Not{HasJac{F}})
> has\_jac{T}(f::T) = istrait(HasJac{T})
> \`\`\`
> 
> Only check the methods table to generate the trait and you're good. Now it auto-finds the trait and \`has\_jac\` is the right value. Thanks for the help!

It makes use of @mauro3 's SimpleTraits.jl. Let me spell it out in more detail since it’s a little tricky.

@mauro3 provided the code which uses `method_exists` to see if a method exists by checking the first arg for a certain type (you can see in the docs that our interface has a value-type in front for each “extra dispatch”)

```julia
check_first_arg(f,T::Type) = check_first_arg(typeof(f),T)
function check_first_arg{F}(::Type{F}, T::Type)
    typ = Tuple{Any, T, Vararg}
    for m in Base.MethodList(F.name.mt) # F.name.mt gets the method-table
        m.sig<:typ && return true
    end
    return false
end

```

However, if you `@code_llvm` that, you’ll see that (because I think the MethodList is global?) that the code is huge and it actually is not as fast as you’d hope. So then we use an internal function:

```julia
__has_jac(f) = check_first_arg(f, Val{:jac})

```

to check for the dispatch, and use that internal function to apply a trait:

```julia
@traitdef HasJac{F}
@generated SimpleTraits.trait{F}(::Type{HasJac{F}}) = __has_jac(F) ? :(HasJac{F}) : :(Not{HasJac{F}})

```

Since checking for traits is a compile-time check, the following is then what we really wanted:

```julia
has_jac{T}(f::T) = istrait(HasJac{T})

```

In the end, `@code_llvm` compiles `has_jac(f)` to either be a true or a false, and everything works at compile time.

Of course, this can be major overkill depending on your use case. However, we found this solution useful since it allows us to have different branches (and dispatches due to traits) which fully optimize and are type-stable thanks to the fact that the existence of the method ends up as compile-time information.

---

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [November 30, 2016, 9:31am UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/7 "2016-11-30T09:31:14Z")

</div>

That’s a nice explanation, thanks Chris.  
Note that now there is macro-sugar in SimpleTraits.jl for above pattern:

```julia
@traitdef HasJac{F}
@traitimpl HasJac{F} <- __has_jac(F)

```

the second line generates: `@generated SimpleTraits.trait{F}(::Type{HasJac{F}}) = __has_jac(F) ? :(HasJac{F}) : :(Not{HasJac{F}})`. This works for any function `some_check(T)::Bool`.

---

<div class="post-metadata">

**Author:** ![pint](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pint/32/125_2.png) [@pint](https://discourse.julialang.org/u/pint)\
**Post date:** [November 30, 2016, 10:04am UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/8 "2016-11-30T10:04:31Z")

</div>

just some random thoughts, not comprehensive answer.

one usual solution i keep seeing in julia source, is creating a default for the abstract type, and either giving some fallback behavior, or just returning “nothing”.

another usual solution is to give info on the actual type, for example iteratorsize which gives back enum values HasLength() | HasShape() | IsInfinite() | SizeUnknown(). this way an implementor can communicate attributes of a subtype back to the common code. the common code decides actions based on this value.

---

<div class="post-metadata">

**Author:** ![Ralph\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ralph_smith/32/10344_2.png) [@Ralph\_Smith](https://discourse.julialang.org/u/Ralph_Smith)\
**Post date:** [December 1, 2016, 5:39am UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/9 "2016-12-01T05:39:40Z")

</div>

One reading of the original question is whether the _specific_ `method2` for a subtype of `Foo` (e.g., `Bar`) exists, as opposed to a method for `Foo` or an intermediate abstract type. This may be tested with

```julia
:method2 in [m.name for m in methodswith(Bar)]

```

Other replies seem to accept the more general methods, and probably they fit your needs, but perhaps this expression will help anyone who (mis-)reads the question as I did. The generality applies to `method_exists` and `applicable`, but I don’t understand how type hierarchy interacts with traits.

While I am at it, I will express the hope that @ChrisRackauckas will find the time to write a blog post about traits, since (a) he is one of the few package writers using them, (b) he writes good blog posts, and (c) his real-world use cases may guide the developers to optimize the implementation of traits in the language proper.

---

<div class="post-metadata">

**Author:** ![zsunberg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/zsunberg/32/1883_2.png) [@zsunberg](https://discourse.julialang.org/u/zsunberg)\
**Post date:** [December 11, 2016, 12:41am UTC](https://discourse.julialang.org/t/how-to-find-if-a-method-is-implemented-for-an-interface/636/10 "2016-12-11T00:41:06Z")

</div>

For the sake of anyone who reads this, we are pursuing a `method_exists`-based scheme with some macros to reduce boilerplate code. Our solvers will check if the user’s `POMDP` type has the required functions like this:

```julia
function POMDPs.solve{S,A,O}(s::CoolSolver, p::POMDP{S,A,O})

    # register requirements
    @check_requirements "CoolSolver" begin
        PType = typeof(p)
        @req discount(::PType)
        @req states(::PType)
        @req actions(::PType)
        @req transition(::PType, ::S, ::A)
        s = first(states(p))
        a = first(actions(p))
        t_dist = transition(p, s, a)
        @req rand( ::AbstractRNG, ::typeof(t_dist))
    end

    # do the work of solving the pomdp
    # ...
end

```

which will output something like this if `rand` is missing

 ![](https://global.discourse-cdn.com/julialang/original/3X/1/c/1c0f131b6868b68b703e6e2323636c08a2843944.png)

For more discussion, see

> <https://github.com/JuliaPOMDP/POMDPs.jl/issues/117>
>
> Hey guys, cool news: switching to empty generic functions (#110) makes it pretty… easy for a solver to check whether the methods it needs are present. I have implemented a way to do this. A solver can check for required functions at solve time as follows (\`solve()\` just returns true if the requirements are met here):
> 
> \`\`\`julia
> module MyModule
> using POMDPs
>     
> export CoolSolver, solve
> 
> type CoolSolver \<: Solver end
> 
> function POMDPs.solve{S,A,O}(s::CoolSolver, p::POMDP{S,A,O})
> 
> # register requirements
> reqs = RequirementsList("CoolSolver")
> push!(reqs, discount, Tuple{typeof(p)})
> push!(reqs, states, Tuple{typeof(p)})
> push!(reqs, actions, Tuple{typeof(p)})
> push!(reqs, transition, Tuple{typeof(p), S, A})
> 
> # determine the distribution type and register the requirement for rand
> @try\_with\_reqs begin
> s = first(states(p))
> a = first(actions(p))
> t\_dist = transition(p, s, a)
> push!(reqs, rand, Tuple{AbstractRNG, typeof(t\_dist)})
> end reqs
> 
> # check requirements and output list if any are missing
> return check\_requirements(reqs, output=:ifmissing)
> end
> end
> \`\`\`
> 
> This will output lists of implemented and missing functions like this:
> 
> !\[image\](https://cloud.githubusercontent.com/assets/4240491/20994065/f99fc018-bca2-11e6-94ae-e364065fe5dc.png)
> 
> The following screenshot shows a longer example. First the problem writer only implements \`discount\` (\`actions\` is already implemented for problems with boolean actions) and tries to run the solver. It tells him that he needs to implement \`states\` and \`transition\`, so he implements those. Now the solver knows enough to determine that he also needs \`rand\` and informs him of this. Finally once \`rand()\` has been implemented, all the requirements have been met.
> 
> !\[image\](https://cloud.githubusercontent.com/assets/4240491/20994016/b36fb2ba-bca2-11e6-959c-4524850258d8.png)
> 
> This is only my first pass, so what feedback do y'all have? Does this seem intuitive enough?
