Patching without adding dependencies

Let’s say I created some package MyPackage that I would like to interact with a package TheirPackage that I did not create. Is there any way to override some of the functions of TheirPackage without having to add TheirPackage to MyPackage’s dependencies? For example, if MyPackage has a type

struct MyVectorType{T} <: AbstractVector{T}
    arr::Vector{T}
end

Base.setindex!(x::MyVectorType, v, ind...) = setindex!(x.arr, v, ind...)
Base.getindex(x::MyVectorType, ind...) = getindex(x.arr, ind...)

Base.length(x::MyVectorType) = length(x.arr)
Base.size(x::MyVectorType) = size(x.arr)

and TheirPackage has a function that isn’t generic enough to take in any AbstractVector but probably should be

theirfunction(x::Vector) = x.^2

Is there a way to extend

TheirPackage.theirfunction(x::AbstractVector) = x.^2

or, I guess more safely

TheirPackage.theirfunction(x::MyVectorType) = x.^2

so if someone just happened to want to use MyVectorType with TheirPackage they could? Since the purpose of MyPackage is more general than just using it with TheirPackage, it doesn’t make sense to have it as a dependency. I guess this is something close to what recipes are for Plots.jl.

The only thing I can think of is defining a new package MyPackagePatches that can be imported for users who want to use MyPackage with packages that need patching, but that seems pretty convoluted.

You can do this with Requires.jl (you’re describing pretty much the textbook use case for that package). I would recommend your second option (defining theirfunction on MyVectorType) to avoid type piracy.

On the other hand, in the case that you specified it might be even more effective to simply open a PR to make TheirPackage more generic. That would help even more people with their own AbstractVector types.

3 Likes

That’s exactly what I was looking for, thanks. I submitted a PR for the package in question a little while back but it hasn’t been accepted yet so I figured I’d just patch it on my side for the time being.