The Compat package is designed to ease interoperability between
older and newer versions of the Julia
language. In particular, in cases where it is
impossible to write code that works with both the latest Julia
master branch and older Julia versions, or impossible to write code
that doesn't generate a deprecation warning in some Julia version, the
Compat package provides a macro that lets you use the latest syntax
in a backwards-compatible way.
This is primarily intended for use by other Julia packages, where it is important to maintain cross-version compatibility.
To use Compat in your Julia package, add a line Compat to the
REQUIRE file in your package directory. Then, in your package,
shortly after the module statement include lines like these:
using Compat
import Compat.Stringand then as needed add
@compat ...compat syntax...wherever you want to use syntax that differs in the latest Julia
master (the development version of Julia). The compat syntax is usually
the syntax on Julia master. However, in a few cases where this is not possible,
a slightly different syntax might be used.
Please check the list below for the specific syntax you need.
Currently, the @compat macro supports the following syntaxes:
-
@compat foo(::CartesianRange{N})to replace the formerfoo(::CartesianRange{CartesianIndex{N}})(#20974). Note thatCartesianRangenow has two type parameters, so using them as fields in otherstructs requires manual intervention. -
Required keyword arguments (#25830). For example,
@compat foo(; x, y)makesxandyrequired keyword arguments: when callingfoo, an error is thrown ifxoryis not explicitly provided.
-
using Compat.Test,using Compat.SharedArrays,using Compat.Mmap, andusing Compat.DelimitedFilesare provided on versions older than 0.7, where these are not yet part of the standard library. (#23931) -
using Compat.Base64is provided on versions older than 0.7, where this library is not yet a part of the standard library. (#24361) -
using Compat.Datesis provided on versions older than 0.7, where this library is not yet a part of the standard library. (#24459) -
using Compat.Unicodeis provided on versions older than 0.7, where this library is not yet a part of the standard library. (#25021) -
using Compat.Printfis provided on versions older than 0.7, where this library is not yet a part of the standard library. (#25056) -
using Compat.SparseArraysis provided on versions older than 0.7, where this library is not yet part of the standard library (#25249). -
using Compat.LinearAlgebrais provided on versions older than 0.7, where this library is not yet part of the standard library (#25571). -
using Compat.Randomis provided on versions older than 0.7, where this library is not yet part of the standard library (#24874). -
using Compat.Libdlis provided on versions older than 0.7, where this library is not yet part of the standard library (#25459). -
using Compat.REPLis provided on versions older than 0.7, where this library is not yet part of the standard library (#25544). -
using Compat.Serializationis provided on versions older than 0.7, where this library is not yet part of the standard library (#25628). -
using Compat.Distributedis provided on versions older than 0.7, where this library is not yet part of the standard library (#24443). -
using Compat.Pkgis provided on versions older than 0.7, where this library is not yet part of the standard library (#25705). Note thatCompat.Pkgwill point to the new package manager on 0.7 which does not have a fully compatible API with the old package manager. -
using Compat.InteractiveUtilsis provided on versions older than 0.7, where this library is not yet part of the standard library (#25780). -
using Compat.LibGit2is provided on versions older than 0.7, where this library is not yet part of the standard library (#25706). -
using Compat.UUIDsis provided on versions older than 0.7, where this library is not yet part of the standard library (#25819). -
using Compat.Markdownis provided on versions older than 0.7, where this library is not yet part of the standard library (#25738). -
using Compat.Socketsis provided on versions older than 0.7, where this library is not yet part of the standard library (#25935) -
using Compat.Statisticsis provided on versions older than 0.7, where this library is not yet part of the standard library (#27834).
-
Compat.readlinewithkeepkeyword argument (#25646) -
Compat.eachlinewithkeepkeyword argument (#25646) -
Compat.readuntilwithkeepkeyword argument (#25646) -
The
isabstract,parameter_upper_bound,typenamereflection methods were added in Julia 0.6. This package re-exports these from theCompat.TypeUtilssubmodule. On earlier versions of julia, that module contains the same functions, but operating on the pre-0.6 type system representation. -
Compat.invokelatestsupports keywords (#22646). -
@__MODULE__is aliased tocurrent_module()for Julia versions 0.6 and below. Versions ofBase.binding_module,expand,macroexpand, andinclude_stringwere added that accept a module as the first argument. (#22064) -
Cmdelements can be accessed as if theCmdwere an array of strings for 0.6 and below (#21197). -
Val(x)constructsVal{x}(). (#22475) -
The
reshapeandntupleAPIs are extended to supportVal{x}()arguments on 0.6 and below. -
logdetforNumbers (#22629). -
fieldcountis equivalent tonfieldsfor Julia versions 0.6 and below and is used to determine the number of fields in a data type (#22350). -
There are versions of
InexactError,DomainError, andOverflowErrorthat take the same arguments as introduced in Julia 0.7-DEV (#20005, #22751, #22761). -
Base.rtoldefaulthow takes a third parameteratol. The two argument form is deprecated in favor of the three arguments form withatol=0. -
The
correctedoptional argument ofcovbecomes a keyword argument ofCompat.Statistics.cov(#21709). -
isequal,==andinhave one argument "curried" forms. For exampleisequal(x)returns a function that compares its arguments toxusingisequal(#26436). -
*(::Union{Char,AbstractString},::Union{Char,AbstractString})concatenation. (#22512) -
diagmandspdiagmaccept pairs mapping diagonals to vectors (#24047, #23757) -
Constructors for
Matrix{T},Array{T}, andSparseMatrixCSC{T}fromUniformScaling(#24372, #24657) -
Constructor for
MatrixfromUniformScaling(#24372, #24657). -
UndefInitializerandundefwith correspondingArrayconstructors (#24652, #26316). -
@compat finalizer(func, obj)with the finalizer to run as the first argument and the object to be finalized as the second (#24605). -
IOContextaccepting key-valuePairs (#23271). -
pairsfor iterating over key-valuePairs (#22907). -
getdo-block syntax supported when usingENV(#23412). -
Some{T}wrapsTto signify that a result ofT<:Voidis expected (#23642). -
replaceaccepts a pair of pattern and replacement, with the number of replacements as a keyword argument (#25165). -
CartesianIndicesandLinearIndicestypes represent cartesian and linear indices of an array (respectively), and indexing such objects allows translating from one kind of index to the other (#25113). -
codeunits(s)returns an array-like view of theUInt8code units of a string andncodeunits(s)returns the number of code units (#25241).codeunit(s)returns the type of the code units ofs(#24999). -
thisind(s, i)returns the character index for codeuniti(#24414). -
Three-argument methods
prevind(s,i,n),nextind(s,i,n)(#23805), andlength(s,i,j)(#24999); the latter two replacechr2indandind2chrin Julia 0.7, respectively. -
printstyledprints to a given stream optionally in color and/or bolded (#25522). -
Dates.Periodrounding (e.g.,round(Dates.Hour(36), Dates.Day, RoundNearestTiesUp) == Dates.Day(2)(#24182). -
firstindexto obtain the first index of an iterable (#25458). -
Compat.namessupporting keyword arguments forallandimported(#25647). -
Compat.IOBuffersupporting keyword arguments (#25873). -
Compat.rangesupporting positional and keyword arguments flavors (#25896), (#28708). -
Compat.trunc,Compat.floor,Compat.ceil,Compat.round, take a keyword argument forbaseanddigits,Compat.roundalso takessigdigits(#26156, #26670). -
Compat.mvandCompat.cpwithforcekeyword argument (#26069). -
Compat.accumulate,Compat.accumulate!,Compat.all,Compat.any,Compat.cumprod,Compat.cumprod!,Compat.cumsum,Compat.cumsum!,Compat.findmax,Compat.findmin,Compat.mapreduce,Compat.maximum,Compat.Statistics.mean,Compat.Statistics.median,Compat.minimum,Compat.prod,Compat.reduce,Compat.sort, andCompat.sumwithdimskeyword argument (#25989,#26369). -
Compat.mapreduceandCompat.reducewithinitkeyword argument (#27711). -
selectdimto obtain a view of an array with a specified index for a specified dimension (#26009). -
Compat.catwithdimsas keyword argument (#27163) -
Single-argument
permutedims(x)for matrices and vectors (#24839). -
fetchforTasks (#25940). -
Compat.qrtakespivotas aValinstance (#22475). -
Compat.Sys.whichandCompat.Sys.isexecutable(#26559, #27298). -
Compat.rmul!provides a subset of the functionality ofLinearAlgebra.rmul!for use with Julia 0.6 (#25701, #25812). -
isbits(t::Type)is nowisbitstype(t)(#26850). -
somethingto get the first argument different fromnothing, unwrapping those of theSometype (#27258). -
mapsliceswithdimskeyword argument (#27828).
-
Displayis nowAbstractDisplay(#24831). -
reprmime(mime, x)is nowrepr(mime, x)(#25990) andmimewritableis nowshowable(#26089). -
is_apple,is_bsd,is_linux,is_unix, andis_windowsare nowSys.isapple,Sys.isbsd,Sys.islinux,Sys.isunix, andSys.iswindows, respectively. These are available in theCompat.Syssubmodule. (#22182) -
readstringis replaced by methods ofread. (#22864)read(::IO, ::Type{String}),read(::AbstractString, ::Type{String}), andread(::AbstractCmd, ::Type{String})are defined for 0.6 and below. -
Rangeis nowAbstractRange(#23570) -
select* functions (select,select!,selectperm,selectperm!) are renamed topartialsort* (partialsort,partialsort!,partialsortperm,partialsortperm!) (#23051) -
ctransposeandctranspose!are nowadjointandadjoint!(#23235) -
Math constants (
π,pi,e,γ,eulergamma,catalan,φ,golden) are moved to theMathConstantsmodule (available asCompat.MathConstants). The name exported fromBaseforeis changed toℯ. (#23427) -
IntSetis nowBitSet(#24282) -
strwidthandcharwidthare now merged intotextwidth(#23667). -
Complex32,Complex64, andComplex128are nowComplexF16,ComplexF32, andComplexF64, respectively (#24647). -
traceis nowtr, available asCompat.tr(#26365). -
JULIA_HOMEis nowSys.BINDIR, available in theCompat.Syssubmodule. (#25102) -
Associativeis nowAbstractDict(#25012). -
indicesis nowaxes(#25057). This function is not exported from Compat to avoid conflicts with AxisArrays and other such packages. -
Voidis nowNothingwith an aliasCvoidfor C interop (#25162). -
unshift!andshift!are nowpushfirst!andpopfirst!(#25100). -
Base.IteratorSizeandBase.IteratorEltypeare available asCompat.IteratorSizeandCompat.IteratorEltype(#25402). -
copy!andunsafe_copy!are nowcopyto!andunsafe_copyto!(#24808). -
contains(haystack, needle)is nowoccursin(needle, haystack)(#26283).occursinalso has a new method forCharneedles (#22435). -
ismatch(r::Regex, str::AbstractString, offset=0)is nowoccursin(r, str)andoccursin(r, str, offset = offset)respectively (#24673,#26283). -
ipermute!is nowinvpermute!(#25168). -
module_parent,Base.function_module, andBase.datatype_moduleare now methods of a new function calledparentmodule(#25629). -
module_name,Base.function_name, andBase.datatype_nameare now methods of a new function callednameof(#25622). -
findis nowfindall(#25545). -
searchis nowfindfirst/findnextandrsearchis nowfindlast/findprev, sometimes combined withisequalorin(#24673, #26436). -
Compat.findfirst,Compat.findnext,Compat.findlastandCompat.findprev, returnnothingwhen no match is found (rather than0or0:-1) as on Julia 0.7 (#24673, #26149). -
findin(a, b)is nowfindall(in(b), a)(#24673). -
indminandindmaxare nowargminandargmax, respectively (#25654). -
Compat.indexinaccepts any iterable as first argument, returnsnothing(rather than0) for entries with no match and gives the index of the first (rather than the last) match (#25662, #25998). -
isabstractandisleaftypeare nowisabstracttypeandisconcretetype, respectively (#23666, #25496). -
gcandgc_enableare nowGC.gcandGC.enable, respectively (#25616). -
endofis nowlastindex(#25458). (Note thatlastindex(A, n)is not supported.) -
nb_availableis nowbytesavailable(#25634). -
method_existsis nowhasmethod(#25615). -
object_idis nowobjectid(#25615). -
DevNull,STDIN,STDOUTandSTDERRare nowdevnull,stdin,stdoutandstderrrespectively (#25959). -
LinSpaceis nowLinRange(#25896). -
isupper,islower,ucfirstandlcfirstare nowisuppercase,islowercase,uppercasefirstandlowercasefirst(#26442). -
Compat.splitandCompat.rsplitacceptkeepemptykeyword argument ifsplitteris given as second argument (#26634) -
isalphais nowisletter(#27077). -
cfunctionis now@cfunction(#26486). -
Unicode.isnumericis now available asisnumeric(#25479). -
vecnormandvecdotare nowCompat.normandCompat.dot, respectively, while the oldnorm(A::AbstractMatrix, p=2)is nowCompat.opnorm(#27401).import Compat: ⋅to getCompat.dotas the binary operator⋅. -
atan2is now a 2-argument method ofatan(#27253). -
srandis nowCompat.Random.seed!(#28295) -
realminandrealmaxare nowfloatminandfloatmax(#28302) -
repmatis nowrepeat(#26039)
-
@vectorize_1argand@vectorize_2argare deprecated on Julia 0.6 in favor of the broadcast syntax (#17302).Compat.@dep_vectorize_1argandCompat.@dep_vectorize_2argare provided so that packages can still provide the deprecated definitions without causing a depwarn in the package itself before all the users are upgraded.Packages are expected to use this until all users of the deprecated vectorized function have migrated. These macros will be dropped when the support for
0.6is dropped fromCompat. -
@nospecializehas been added (#22666). -
The logging macros
@error,@warn,@infoand@debugcan be used asCompat.@error,Compat.@warn,Compat.@infoandCompat.@debugon Julia 0.6 (#24490). Note that the behavior do not mirror the logging macros in Julia 0.7, instead on Julia 0.6:- Messages are printed to
STDERR(likeinfoandwarnon Julia 0.6) and not to a dedicated logging stream. - The loglevel can not be controlled, but
Compat.@debugmessages can be turned on/off by callingCompat.enable_debug(true/false). - Extra metadata sent to the macros are ignored.
As an alternative, see the MicroLogging.jl package for a logging interface similar to the one in Julia 0.7.
- Messages are printed to
-
On versions of Julia that do not contain a Base.Threads module, Compat defines a Threads module containing a no-op
@threadsmacro. -
The
Expr(:macrocall)has an extra initial argument__source__, which can be tested for withCompat.macros_have_sourceloc.
Compat.AbstractDateTimeis an alias forCompat.Dates.AbstractDateTimeas of (#25227) andCompat.Dates.TimeTypeprior to that.
One of the most important rules for Compat.jl is to avoid breaking user code
whenever possible, especially on a released version.
Although the syntax used in the most recent Julia version
is the preferred compat syntax, there are cases where this shouldn't be used.
Examples include when the new syntax already has a different meaning
on previous versions of Julia, or when functions are removed from Base
Julia and the alternative cannot be easily implemented on previous versions.
In such cases, possible solutions are forcing the new feature to be used with
qualified name in Compat.jl (e.g. use Compat.<name>) or
reimplementing the old features on a later Julia version.
If you're adding additional compatibility code to this package, the contrib/commit-name.sh script in the base Julia repository is useful for extracting the version number from a git commit SHA. For example, from the git repository of julia, run something like this:
bash $ contrib/commit-name.sh a378b60fe483130d0d30206deb8ba662e93944da
0.5.0-dev+2023This prints a version number corresponding to the specified commit of the form
X.Y.Z-aaa+NNNN, and you can then test whether Julia
is at least this version by VERSION >= v"X.Y.Z-aaa+NNNN".
One of the most frequent problems package developers encounter is finding the right
version of Compat to add to their REQUIRE. This is meant to be a guide on how to
specify the right lower bound.
-
Find the appropriate fix needed for your package from the
CompatREADME. Every function or feature added toCompatis documented in its README, so you are guaranteed to find it. -
Navigate to the blame page of the README by clicking on the README file on GitHub, and then clicking on the
blamebutton which can be found in the top-right corner. -
Now find your fix, and then find the corresponding commit ID of that fix on the left-hand side. Click on the commit ID. This navigates to a page which recorded that particular commit.
-
On the top pane, you should find the list of the tagged versions of Compat that includes this fix. Find the minimum version from there.
-
Now specify the correct minimum version for Compat in your REQUIRE file by
Compat <version>