Backporting new Julia features in old versions of Julia

Let’s say that there is a simple new feature in Julia 1.9 that I would like to use in my library. However, for various reasons I need to keep my library compatible with older Julia versions as well. Is there a standard way I can backport this new Julia feature, without having to copy the code myself?

As an example, I want to use Returns(1) in my Julia library. But I also want to allow users to download the latest version of my library for Julia 1.6 (say, a group in industry wants to use recent patches of my library, but also uses LTS Julia for whatever internal reason).

So, rather than:

  1. Avoiding new features, or
  2. maintaining two versions of my code,

I just copied the source code into my library:

if VERSION < v"1.7"
    @eval struct Returns{V} <: Function
        value::V
        Returns{V}(value) where {V} = new{V}(value)
        Returns(value) = new{typeof(value)}(value)
    end
    @eval (obj::Returns)(@nospecialize(args...); @nospecialize(kw...)) = obj.value
end

And used Returns(1) as normal in my code. I have started accumulating a few other features which I wanted to use: randn(::Type{BigFloat}) (copied), @inline(f(x)) (no-op on earlier versions of Julia).

But this seems like it would be a common issue, so perhaps there is a better way. For example, while you may correctly point out potential issues with this: there is from __future__ import print_function in Python, for importing new features in backwards compatible code.

Perhaps there is some Julia library I have missed which defines many of the new features in such a way that I can:

  1. Import them on old versions of Julia, or
  2. No-op on new versions of Julia?

Like:

import Future: Returns, @inline, randn

which would import new definitions of these on old versions, and do nothing on new versions. (Of course, it wouldn’t need to backport everything, just the most popular new features which are otherwise backwards-compatible)

Is there something like this out there?

1 Like
2 Likes

Amazing. Thanks!

Side note: I think Compat.jl is an ambiguity-generating package name.

I realized that I’ve actually been told about Compat.jl before, but I had always thought they meant to just raise my [compat] setting in Project.toml to get the new features (i.e., set julia="1.9"), not that it was an entirely separate package.

I think I had thought that Compat.jl was the Pkg.jl subpackage that handled the compat key.

1 Like