Best practice for not requiring users to load package for package extensions?

I am looking to make loading package extensions transparent to the user of a package, meaning they would not have to manually include the conditional dependency to their environment. For example, if the user calls a function with a specific option enabled, then that function would add the dependency for the user:

function a(x::Bool)
	if x
		using Pkg
		Pkg.add("package")
		if !isdefined(Base, :get_extension)
  			include("../ext/PackageExt.jl")
  		end
	end
end

I’m wondering if the use of Pkg in this instance is considered best practice or if there is a more idiomatic approach for such.

While I understand the intent, I think leaving control of the dependencies to the user is a fairly reasonable thing to do. Automatic install is not the norm in the Julia ecosystem, and using Pkg is so simple that it probably should stay that way.
Maybe provide a useful error message in the default implementation of the function, and overload said implementation with an extension method?

1 Like

I would add that decoupling package installation from usage is one of the things that improved user experience in Julia a lot. People is willing to wait for packages to install much more than what they are willing to wait functions to work when they try. And with code cashing the difference of both steps increased a lot (one is much slower, the other much faster), so the user will notice that even further.

Thank you for both of your answers. I’ll adopt the error pattern.