How to execute code depending on julia version

How can I conditionally execute some code, depending on what julia version it is running on?

Specifically I test for type stability using @inferred.
For some code this succeeds in Julia 1.7 but fails in Julia 1.6. Instead of removing the @inferred entirely, I would like to test the Julia version and include the code line with @inferred only if running on version >=1.7.

julia> VERSION
v"1.7.0"

julia> fieldnames(typeof(VERSION))
(:major, :minor, :patch, :prerelease, :build)

julia> Int.([VERSION.major, VERSION.minor])
2-element Vector{Int64}:
 1
 7
@static if VERSION ≥ v"1.7"
    # do something
end

(The reason for the @static is so that this check occurs at compile time, which is sometimes important, e.g. if you want to ccall a function that doesn’t exist before a certain version then you want to strip it out before compilation.)

You should almost never have to look inside the fields of a VersionNumber (== typeof(VERSION)) object. Just do comparisons with v"..." strings as above. See also the manual on version number literals.

(I noticed that the VersionNumber docs don’t talk about comparisons, so I created a PR improving them: julia#43893.)

5 Likes

What’s the “right” way to write a check like VERSION >= v"1.8", but that also returns true for nightlies/pre-releases of that julia version?

VERSION >= v"1.8-"

2 Likes