Extensions/weakdeps loading and package design

I just experimented for the first time the implementation of a package extension. Everything worked, but as I did it I need to load explicitly the weak dependency for the extension module to be loaded.

So my package looks like:

module MyPackage
    export foo
    function foo(args...; kargs...)
        error("Need to load StaticArrays for foo to work")
    end
end

module FooExt
    import MyPackage: foo
    using StaticArrays
    foo(x::SVector) = x
end

This works, but I did not find a documented indication that I need (or that is a good idea) to provide a sensible error message by defining a generic foo(args...) in the main package. Is that reasonable? Is there another default way to inform the user that the weakdep has to be loaded?

In your opinion, would the clarifications proposed in this PR have helped you understand how extensions are meant to be used?

The PR mentions the definition of an empty function foo end, but I think defining a generic fallback is a good idea in your case, because it gives the user actionable information about what to do: simply load the required package for the extension code to kick in.

2 Likes

That is a nice addition to the docs. I maybe would be even more explicit and suggest the error message or a “not implemented method”.

@gdalle Do you have any thoughts on this?

I’m torn.
On the one hand, I usually prefer a MethodError to a hardcoded error("this is not implemented"), it is the natural result of a method not existing.
On the other hand, I have often had the issue of an extension not loading, only diguised as a weird MethodError coming out of nowhere. An explicit mention of the extension in the error message would have helped me then.

1 Like

I certainly prefer the most informative message and will use that in my package. If that is something to be recommended in general I’m not sure.

You could register an error hint for MethodError.

1 Like

What you mean by “register” there?

https://docs.julialang.org/en/v1/base/base/#Base.Experimental.register_error_hint

This is still experimental, though

3 Likes

Seems more convoluted than the custom error message. What’s the advantage?

Here’s an example of such an error hint. The advantage is that you can be intentional about the MethodError which might under other circumstances signal a user error. But I agree it’s a bit convoluted.