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.String
and 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.:bar
-foo.(:bar)
in 0.4 (#15032). -
@compat f.(args...)
-broadcast(f, args...)
in 0.4 (#15032). -
@compat (a::B{T}){T}(c) = d
- the Julia 0.5-style call overload. -
@compat Dict(foo => bar, baz => qux)
- type-inferredDict
construction. (Also works forDataStructures.OrderedDict
) -
@compat Dict{Foo,Bar}(foo => bar, baz => qux)
- type-declaredDict
construction. (Also works forDataStructures.OrderedDict
) -
@compat(get(io, s, false))
, withs
equal to:limit
,:compact
or:multiline
, to detect the corresponding print settings (performs useful work only on Julia 0.5, defaults tofalse
otherwise) -
@compat split(str, splitter; keywords...)
- the Julia 0.4-style keyword-basedsplit
function -
@compat rsplit(str, splitter; keywords...)
- the Julia 0.4-style keyword-basedrsplit
function -
@compat Float64(x)
,@compat UInt8(x)
, - the Julia 0.4-style numeric types constructor. -
@compat Tuple{foo, bar}
- Julia 0.4-style tuple types. -
@compat chol(A, Val{:U})
- Julia 0.4 type-stable cholesky factorizations (will not be type-stable on 0.3) -
@compat f(t::Timer)
- mimic the Julia 0.4 Timer class -
@compat Vector{Int}()
,@compat Vector{UInt8}(n)
,@compat Array{Float32}(2,2)
- Julia 0.4-style array constructors. -
@compat Void
-Nothing
on 0.3 (Ptr{Void}
is not changed). -
@compat Union{args...}
-Union(args...)
on 0.3. #11432 -
@compat withenv(f, "a" => a, "b" => b...)
on 0.3. -
@compat import Base.show
and@compat function show(args...)
for handling the deprecation ofwritemime
in Julia 0.5 ([#16563]). See JuliaLang#219.
-
String
has undergone multiple changes: in Julia 0.3 it was an abstract type and then got renamed toAbstractString
in 0.4; in 0.5,ASCIIString
andByteString
were deprecated, andUTF8String
was renamed to the (now concrete) typeString
.Compat provides unexported
Compat.UTF8String
andCompat.ASCIIString
type aliases which are equivalent to the same types from Base on Julia 0.3 and 0.4, but toString
on Julia 0.5. In most cases, using these types by callingimport Compat: UTF8String, ASCIIString
should be enough. Though note thatCompat.ASCIIString
does not guarantee that the string only contains ASCII characters on Julia 0.5: callisascii
to check if the string is pure ASCII if needed.Compat also provides an unexported
Compat.String
type which is equivalent toByteString
on Julia 0.3 and 0.4, and toString
on Julia 0.5. This type should be used only in places whereByteString
was used on Julia 0.3 and 0.4, i.e. where eitherASCIIString
orUTF8String
should be accepted. It should not be used as the default type for variables or fields holding strings, as it introduces type-instability in Julia 0.3 and 0.4: useCompat.UTF8String
orCompat.ASCIIString
instead. -
bytestring
has been replaced in most cases with additionalString
construction methods; for 0.3 compatibility, the usage involves replacingbytestring(args...)
with@compat String(args...)
. However, for converting aPtr{UInt8}
to a string, use the newunsafe_string(...)
method to make a copy orunsafe_wrap(String, ...)
to avoid a copy. -
typealias AbstractString String
-String
has been renamed toAbstractString
in Julia 0.4 #8872 -
typealias AbstractFloat FloatingPoint
-FloatingPoint
has been renamed toAbstractFloat
#12162 -
typealias AssertionError ErrorException
-AssertionError
was introduced in #9734; before@assert
threw anErrorException
-
For all unsigned integer types to their equivalents with uppercase
I
. #8907 -
Cstring
andCwstring
forPtr{UInt8}
andPtr{Cwchar_t}
, respectively: these should be used for passing NUL-terminated strings toccall
. (In Julia 0.4, using these types also checks whether the string has embedded NUL characters #10994.) -
typealias Irrational MathConst
-MathConst
has been renamed toIrrational
#11922 -
typealias UDPSocket UdpSocket
-UdpSocket
has been renamed toUDPSocket
#8175 -
typealias Base64EncodePipe Base64Pipe
-Base64Pipe
has been renamed toBase64EncodePipe
#9157 -
typealias OutOfMemoryError MemoryError
-MemoryError
has been renamed toOutOfMemoryError
#10503
-
eachindex
, as infor i in eachindex(A)
, can be used in Julia 0.3. This is the recommended way to iterate over each index in anAbstractArray
. On Julia 0.3eachindex
just returns1:length(A)
, but in Julia 0.4 it can return a more sophisticated iterator. -
isdiag
, which tests whether a matrix is diagonal, can be used in Julia 0.3. -
keytype
andvaltype
, which return key and value type of Associative type, can be used in Julia 0.3. -
tryparse
, which is a variant onBase.parse
that returns aNullable
, can be used in Julia 0.3. -
fma(x,y,z)
andmuladd(x,y,z)
can be used in Julia 0.3 forx*y+z
. -
Timer(timeout::Real, repeat::Real=0.0)
andTimer(cb::Function, timeout::Real, repeat::Real=0.0)
allow Julia 0.4-style Timers to be constructed and used. -
__precompile__(iscompiled::Bool)
andinclude_dependency(path::AbstractString)
allow Julia 0.4 precompilation information to be provided (with no effect in earlier versions). (However, to enable precompiling in 0.4, it is better to explicitly putVERSION >= v"0.4.0-dev+6521" && __precompile__()
before yourmodule
statement, so that Julia knows to precompile before anything in your module is evaluated.) -
isapprox(A, B)
for arrays (JuliaLang/julia#12472), and synonyms≈
(U+2248, LaTeX\approx
) and≉
(U+2249, LaTeX\napprox
) forisapprox
and!isapprox
, respectively. -
withenv
can be used in Julia 0.3 (see the 0.4 docs). Note that you must prepend calls towithenv
with@compat
if you'd like to use it with the=>
syntax. -
foreach
, similar tomap
but when the return value is not needed (#13744). -
walkdir
, returns an iterator that walks the directory tree of a directory. (#13707) -
allunique
, checks whether all elements in an iterable appear only once (#15914).
-
pointer_to_array
andpointer_to_string
have been replaced withunsafe_wrap(Array, ...)
andunsafe_wrap(String, ...)
respectively. -
bytestring(::Ptr, ...)
has been replaced withunsafe_string
. -
itrunc
,iround
,iceil
,ifloor
are now accessed viatrunc(T, x)
, etc. (#9133). Truncated conversions between integer types are nown % T
(#8646). -
Base.Random.randmtzig_exprnd
is nowrandexp
#9144 -
sizehint
is nowsizehint!
#9278 -
Base.IPv4
andBase.IPv6
can now acceptString
s as constructor arguments #9346 -
randbool()
is nowrand(Bool)
andrandbool([dims])
is nowbitrand([dims])
#9569 -
beginswith
is nowstartswith
#9583 -
names(::DataType)
is now renamed tofieldnames
#10332 -
parseint
andparsefloat
are nowparse(T, ...)
#10543; along the same lineBigFloat(s::String)
is nowparse(BigFloat,s)
#10955. -
convert(::Ptr{T}, x)
is nowBase.unsafe_convert
#9986. Compat provides an unexportedCompat.unsafe_convert
method that is aliased toBase.convert
on Julia 0.3 andBase.unsafe_convert
on Julia 0.4. -
gc_enable()
is nowgc_enable(true)
andgc_disable()
is nowgc_enable(false)
#11647 -
base64
is nowbase64encode
#9157 -
super
is nowsupertype
#14338 -
qr(A, pivot=b)
is nowqr(A, Val{b})
, likewise forqrfact
andqrfact!
-
readall
andreadbytes
are nowreadstring
andread
#14660 -
get_bigfloat_precision
is nowprecision(BigFloat)
,set_precision
issetprecision
andwith_bigfloat_precision
is now alsosetprecision
#13232 -
get_rounding
is nowrounding
.set_rounding
andwith_rounding
are nowsetrounding
#13232 -
Base.tty_size
(which was not exported) is nowdisplaysize
in Julia 0.5. -
Compat.LinAlg.checksquare
#14601 -
issym
is nowissymmetric
#15192 -
istext
is nowistextmime
#15708 -
symbol
is nowSymbol
#16154; use@compat Symbol(...)
if you need Julia 0.3 compatibility. -
write(::IO, ::Ptr, len)
is nowunsafe_write
#14766. -
slice
is nowview
#16972 doimport Compat.view
and then useview
normally without the@compat
macro.
-
@static
has been added #16219. -
@inline
and@noinline
have been added. On 0.3, these are "no-ops," meaning they don't actually do anything. -
@functorize
(not present in any Julia version) takes a function (or operator) and turns it into a functor object if one is available in the used Julia version. E.g. something likemapreduce(Base.AbsFun(), Base.MulFun(), x)
can now be written asmapreduce(@functorize(abs), @functorize(*), x)
, andf(::Base.AbsFun())
asf(::typeof(@functorize(abs)))
, to work across different Julia versions.Func{1}
can be written assupertype(typeof(@functorize(abs)))
(and so on forFunc{2}
), which will fall back toFunction
on Julia 0.5.
-
Dict(ks, vs)
is nowDict(zip(ks, vs))
#8521 -
Libc and dynamic library-related functions have been moved to the Libc and Libdl modules #10328
-
zero(Ptr{T})
is nowPtr{T}(0)
#8909 -
The unexported macro
Base.@math_const
was renamed toBase.@irrational
, accessible asCompat.@irrational
on either 0.3 or 0.4 #11922 -
remotecall
,remotecall_fetch
,remotecall_wait
, andremote_do
have the function to be executed remotely as the first argument in Julia 0.5. LoadingCompat
defines the same methods in older versions of Julia. #13338 -
Base.FS
is nowBase.Filesystem
#12819. Compat provides an unexportedCompat.Filesystem
module that is aliased toBase.FS
on Julia 0.3 and 0.4 andBase.Filesystem
on Julia 0.5. -
mktemp
andmktempdir
now have variants which take a function as their first argument for automated cleanup. #9017 -
cov
andcor
don't allow keyword arguments anymore. Loading Compat defines compatibility methods for the new API. #13465 -
On versions of Julia that do not contain a Base.Threads module, Compat defines a Threads module containing a no-op
@threads
macro. -
Base.SingleAsyncWork
is nowBase.AsyncCondition
Compat provides an unexportedCompat.AsyncCondition
type that is aliased toBase.SingleAsyncWork
on Julia 0.3 and 0.4 andBase.AsyncCondition
on Julia 0.5. -
repeat
now accepts anyAbstractArray
#14082:Compat.repeat
supports this new API on Julia 0.3 and 0.4, and callsBase.repeat
on 0.5. -
OS_NAME
is nowSys.KERNEL
. OS information available asis_apple
,is_bsd
,is_linux
,is_unix
, andis_windows
. 16219
-
Nullable
types and their associated operations. -
The parametric
Val{T}
"value types" can be used in Julia 0.3.
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 bin/version.sh
script 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 $ /path/to/Compat/bin/version.sh a378b60fe483130d0d30206deb8ba662e93944da
0.5.0-dev+2023
This 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"
.