Julia: create a package with optional dependencies

Viewed 830

I want to build a numerical package that also has optional support for visualization. For simplicity, let's say the respective dependencies are NumPackage for the heavy lifting and VizPackage for optional visualization.

In Julia, how can I build a module that has NumPackage in its required dependencies, but VizPackage only as an optional dependency, say for example for those users that want to run an example simulation and visualize it?

I saw the Requires.jl package but not sure if it's the right tool for what I'm trying to do.

3 Answers

I don't know how to add optional dependencies to a package, but for the specific case of having a dependency on a visualization package, what you can do is create plot recipes. In order to have plot recipes in your package, you only need to depend on RecipesBase.jl, which is a very minimal package. If you create plot recipes for your types you will then be able to use Plots.jl to visualize the information contained in your types, without having an explicit dependency on Plots.jl in your package.

I had the same problem and in some cases needed a dependency on PyPlot because the needed functionality is not there in Plots. OTOH Plots/gr is faster, so in cases where it is sufficient it makes sense to use that one.

I figured out that you can just pass the plot module as an additional parameter to a plotting function and as an optional parameter to a numerical example. You also can have heuristics to distinguish between different plot modules. See e.g. here (I plan to modify this and to add a type annotation Plotter::Union{Module,Nothing}).

So a user would run your package e.g. as follows:

Without plotting:

using NumPackage

NumPackage.run()

With plotting:

using NumPackage
using VizPackage

NumPackage.run(Plotter=VizPackage)

There needs to be no mentioning at all of VizPackage in Project.toml.

Testing and code coverage is another question though...

Jürgen

Related