Julia Base contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection ofavailable packages. Functions are grouped by topic below.
Some general notes:
import Module
to import the module, andModule.fn(x)
to use the functions.using Module
will import all exportedModule
functions into the current namespace.!
) modify their arguments. Some functions have both modifying (e.g.,sort!
) and non-modifying (sort
) versions.The behaviors ofBase
and standard libraries are stable as defined inSemVer only if they are documented; i.e., included in theJulia documentation and not marked as unstable. SeeAPI FAQ for more information.
Base.exit
—Functionexit(code=0)
Stop the program with an exit code. The default exit code is zero, indicating that the program completed successfully. In an interactive session,exit()
can be called with the keyboard shortcut^D
.
Base.atexit
—Functionatexit(f)
Register a zero- or one-argument functionf()
to be called at process exit.atexit()
hooks are called in last in first out (LIFO) order and run before object finalizers.
Iff
has a method defined for one integer argument, it will be called asf(n::Int32)
, wheren
is the current exit code, otherwise it will be called asf()
.
The one-argument form requires Julia 1.9
Exit hooks are allowed to callexit(n)
, in which case Julia will exit with exit coden
(instead of the original exit code). If more than one exit hook callsexit(n)
, then Julia will exit with the exit code corresponding to the last called exit hook that callsexit(n)
. (Because exit hooks are called in LIFO order, "last called" is equivalent to "first registered".)
Note: Once all exit hooks have been called, no more exit hooks can be registered, and any call toatexit(f)
after all hooks have completed will throw an exception. This situation may occur if you are registering exit hooks from background Tasks that may still be executing concurrently during shutdown.
Base.isinteractive
—Functionisinteractive() -> Bool
Determine whether Julia is running an interactive session.
Base.summarysize
—FunctionBase.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int
Compute the amount of memory, in bytes, used by all unique objects reachable from the argument.
Keyword Arguments
exclude
: specifies the types of objects to exclude from the traversal.chargeall
: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.See alsosizeof
.
Examples
julia> Base.summarysize(1.0)8julia> Base.summarysize(Ref(rand(100)))848julia> sizeof(Ref(rand(100)))8
Base.__precompile__
—Function__precompile__(isprecompilable::Bool)
Specify whether the file calling this function is precompilable, defaulting totrue
. If a module or file isnot safely precompilable, it should call__precompile__(false)
in order to throw an error if Julia attempts to precompile it.
Base.include
—FunctionBase.include([mapexpr::Function,] m::Module, path::AbstractString)
Evaluate the contents of the input source file in the global scope of modulem
. Every module (except those defined withbaremodule
) has its own definition ofinclude
omitting them
argument, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls toinclude
will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.
The optional first argumentmapexpr
can be used to transform the included code before it is evaluated: for each parsed expressionexpr
inpath
, theinclude
function actually evaluatesmapexpr(expr)
. If it is omitted,mapexpr
defaults toidentity
.
Julia 1.5 is required for passing themapexpr
argument.
include
—Functioninclude([mapexpr::Function,] path::AbstractString)
Evaluate the contents of the input source file in the global scope of the containing module. Every module (except those defined withbaremodule
) has its own definition ofinclude
, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls toinclude
will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files. The argumentpath
is normalized usingnormpath
which will resolve relative path tokens such as..
and convert/
to the appropriate path separator.
The optional first argumentmapexpr
can be used to transform the included code before it is evaluated: for each parsed expressionexpr
inpath
, theinclude
function actually evaluatesmapexpr(expr)
. If it is omitted,mapexpr
defaults toidentity
.
UseBase.include
to evaluate a file into another module.
Julia 1.5 is required for passing themapexpr
argument.
Base.include_string
—Functioninclude_string([mapexpr::Function,] m::Module, code::AbstractString, filename::AbstractString="string")
Likeinclude
, except reads code from the given string rather than from a file.
The optional first argumentmapexpr
can be used to transform the included code before it is evaluated: for each parsed expressionexpr
incode
, theinclude_string
function actually evaluatesmapexpr(expr)
. If it is omitted,mapexpr
defaults toidentity
.
Julia 1.5 is required for passing themapexpr
argument.
Base.include_dependency
—Functioninclude_dependency(path::AbstractString; track_content::Bool=true)
In a module, declare that the file, directory, or symbolic link specified bypath
(relative or absolute) is a dependency for precompilation; that is, iftrack_content=true
the module will need to be recompiled if the content ofpath
changes (ifpath
is a directory the content equalsjoin(readdir(path))
). Iftrack_content=false
recompilation is triggered when the modification timemtime
ofpath
changes.
This is only needed if your module depends on a path that is not used viainclude
. It has no effect outside of compilation.
Keyword argumenttrack_content
requires at least Julia 1.11. An error is now thrown ifpath
is not readable.
__init__
—Keyword__init__
The__init__()
function in a module executes immediatelyafter the module is loaded at runtime for the first time. It is called once, after all other statements in the module have been executed. Because it is called after fully importing the module,__init__
functions of submodules will be executed first. Two typical uses of__init__
are calling runtime initialization functions of external C libraries and initializing global constants that involve pointers returned by external libraries. See themanual section about modules for more details.
Examples
const foo_data_ptr = Ref{Ptr{Cvoid}}(0)function __init__() ccall((:foo_init, :libfoo), Cvoid, ()) foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Cvoid}, ()) nothingend
Base.which
—Methodwhich(f, types)
Returns the method off
(aMethod
object) that would be called for arguments of the giventypes
.
Iftypes
is an abstract type, then the method that would be called byinvoke
is returned.
See also:parentmodule
,@which
, and@edit
.
Base.methods
—Functionmethods(f, [types], [module])
Return the method table forf
.
Iftypes
is specified, return an array of methods whose types match. Ifmodule
is specified, return an array of methods defined in that module. A list of modules can also be specified as an array.
At least Julia 1.4 is required for specifying a module.
See also:which
,@which
andmethodswith
.
Base.@show
—Macro@show exs...
Prints one or more expressions, and their results, tostdout
, and returns the last result.
Examples
julia> x = @show 1+21 + 2 = 33julia> @show x^2 x/2;x ^ 2 = 9x / 2 = 1.5
Base.MainInclude.ans
—Constantans
A variable referring to the last computed value, automatically imported to the interactive prompt.
Base.MainInclude.err
—Constanterr
A variable referring to the last thrown errors, automatically imported to the interactive prompt. The thrown errors are collected in a stack of exceptions.
Base.active_project
—Functionactive_project()
Return the path of the activeProject.toml
file. See alsoBase.set_active_project
.
Base.set_active_project
—Functionset_active_project(projfile::Union{AbstractString,Nothing})
Set the activeProject.toml
file toprojfile
. See alsoBase.active_project
.
This function requires at least Julia 1.8.
This is the list of reserved keywords in Julia:baremodule
,begin
,break
,catch
,const
,continue
,do
,else
,elseif
,end
,export
,false
,finally
,for
,function
,global
,if
,import
,let
,local
,macro
,module
,quote
,return
,struct
,true
,try
,using
,while
. Those keywords are not allowed to be used as variable names.
The following two-word sequences are reserved:abstract type
,mutable struct
,primitive type
. However, you can create variables with names:abstract
,mutable
,primitive
andtype
.
Finally:where
is parsed as an infix operator for writing parametric method and type definitions;in
andisa
are parsed as infix operators;public
is parsed as a keyword when beginning a toplevel statement;outer
is parsed as a keyword when used to modify the scope of a variable in an iteration specification of afor
loop; andas
is used as a keyword to rename an identifier brought into scope byimport
orusing
. Creation of variables namedwhere
,in
,isa
,outer
andas
is allowed, though.
module
—Keywordmodule
module
declares aModule
, which is a separate global variable workspace. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (viaexport
andpublic
). Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with somebody else’s. See themanual section about modules for more details.
Examples
module Fooimport Base.showexport MyType, foostruct MyType xendbar(x) = 2xfoo(a::MyType) = bar(a.x) + 1show(io::IO, a::MyType) = print(io, "MyType $(a.x)")end
export
—Keywordexport
export
is used within modules to tell Julia which names should be made available to the user. For example:export foo
makes the namefoo
available whenusing
the module. See themanual section about modules for details.
public
—Keywordpublic
public
is used within modules to tell Julia which names are part of the public API of the module . For example:public foo
indicates that the namefoo
is public, without making it available whenusing
the module. See themanual section about modules for details.
The public keyword was added in Julia 1.11. Prior to this the notion of publicness was less explicit.
import
—Keywordimport
import Foo
will load the module or packageFoo
. Names from the importedFoo
module can be accessed with dot syntax (e.g.Foo.foo
to access the namefoo
). See themanual section about modules for details.
using
—Keywordusing
using Foo
will load the module or packageFoo
and make itsexport
ed names available for direct use. Names can also be used via dot syntax (e.g.Foo.foo
to access the namefoo
), whether they areexport
ed or not. See themanual section about modules for details.
When two or more packages/modules export a name and that name does not refer to the same thing in each of the packages, and the packages are loaded viausing
without an explicit list of names, it is an error to reference that name without qualification. It is thus recommended that code intended to be forward-compatible with future versions of its dependencies and of Julia, e.g., code in released packages, list the names it uses from each loaded package, e.g.,using Foo: Foo, f
rather thanusing Foo
.
as
—Keywordas
as
is used as a keyword to rename an identifier brought into scope byimport
orusing
, for the purpose of working around name conflicts as well as for shortening names. (Outside ofimport
orusing
statements,as
is not a keyword and can be used as an ordinary identifier.)
import LinearAlgebra as LA
brings the importedLinearAlgebra
standard library into scope asLA
.
import LinearAlgebra: eigen as eig, cholesky as chol
brings theeigen
andcholesky
methods fromLinearAlgebra
into scope aseig
andchol
respectively.
as
works withusing
only when individual identifiers are brought into scope. For example,using LinearAlgebra: eigen as eig
orusing LinearAlgebra: eigen as eig, cholesky as chol
works, butusing LinearAlgebra as LA
is invalid syntax, since it is nonsensical to renameall exported names fromLinearAlgebra
toLA
.
baremodule
—Keywordbaremodule
baremodule
declares a module that does not containusing Base
or local definitions ofeval
andinclude
. It does still importCore
. In other words,
module Mod...end
is equivalent to
baremodule Modusing Baseeval(x) = Core.eval(Mod, x)include(p) = Base.include(Mod, p)...end
function
—Keywordfunction
Functions are defined with thefunction
keyword:
function add(a, b) return a + bend
Or the short form notation:
add(a, b) = a + b
The use of thereturn
keyword is exactly the same as in other languages, but is often optional. A function without an explicitreturn
statement will return the last expression in the function body.
macro
—Keywordmacro
macro
defines a method for inserting generated code into a program. A macro maps a sequence of argument expressions to a returned expression, and the resulting expression is substituted directly into the program at the point where the macro is invoked. Macros are a way to run generated code without callingeval
, since the generated code instead simply becomes part of the surrounding program. Macro arguments may include expressions, literal values, and symbols. Macros can be defined for variable number of arguments (varargs), but do not accept keyword arguments. Every macro also implicitly gets passed the arguments__source__
, which contains the line number and file name the macro is called from, and__module__
, which is the module the macro is expanded in.
See the manual section onMetaprogramming for more information about how to write a macro.
Examples
julia> macro sayhello(name) return :( println("Hello, ", $name, "!") ) end@sayhello (macro with 1 method)julia> @sayhello "Charlie"Hello, Charlie!julia> macro saylots(x...) return :( println("Say: ", $(x...)) ) end@saylots (macro with 1 method)julia> @saylots "hey " "there " "friend"Say: hey there friend
return
—Keywordreturn
return x
causes the enclosing function to exit early, passing the given valuex
back to its caller.return
by itself with no value is equivalent toreturn nothing
(seenothing
).
function compare(a, b) a == b && return "equal to" a < b ? "less than" : "greater than"end
In general you can place areturn
statement anywhere within a function body, including within deeply nested loops or conditionals, but be careful withdo
blocks. For example:
function test1(xs) for x in xs iseven(x) && return 2x endendfunction test2(xs) map(xs) do x iseven(x) && return 2x x endend
In the first example, the return breaks out oftest1
as soon as it hits an even number, sotest1([5,6,7])
returns12
.
You might expect the second example to behave the same way, but in fact thereturn
there only breaks out of theinner function (inside thedo
block) and gives a value back tomap
.test2([5,6,7])
then returns[5,12,7]
.
When used in a top-level expression (i.e. outside any function),return
causes the entire current top-level expression to terminate early.
do
—Keyworddo
Create an anonymous function and pass it as the first argument to a function call. For example:
map(1:10) do x 2xend
is equivalent tomap(x->2x, 1:10)
.
Use multiple arguments like so:
map(1:10, 11:20) do x, y x + yend
begin
—Keywordbegin
begin...end
denotes a block of code.
begin println("Hello, ") println("World!")end
Usuallybegin
will not be necessary, since keywords such asfunction
andlet
implicitly begin blocks of code. See also;
.
begin
may also be used when indexing to represent the first index of a collection or the first index of a dimension of an array. For example,a[begin]
is the first element of an arraya
.
Use ofbegin
as an index requires Julia 1.4 or later.
Examples
julia> A = [1 2; 3 4]2×2 Array{Int64,2}: 1 2 3 4julia> A[begin, :]2-element Array{Int64,1}: 1 2
end
—Keywordend
end
marks the conclusion of a block of expressions, for examplemodule
,struct
,mutable struct
,begin
,let
,for
etc.
end
may also be used when indexing to represent the last index of a collection or the last index of a dimension of an array.
Examples
julia> A = [1 2; 3 4]2×2 Array{Int64, 2}: 1 2 3 4julia> A[end, :]2-element Array{Int64, 1}: 3 4
let
—Keywordlet
let
blocks create a new hard scope and optionally introduce new local bindings.
Just like theother scope constructs,let
blocks define the block of code where newly introduced local variables are accessible. Additionally, the syntax has a special meaning for comma-separated assignments and variable names that may optionally appear on the same line as thelet
:
let var1 = value1, var2, var3 = value3 codeend
The variables introduced on this line are local to thelet
block and the assignments are evaluated in order, with each right-hand side evaluated in the scope without considering the name on the left-hand side. Therefore it makes sense to write something likelet x = x
, since the twox
variables are distinct with the left-hand side locally shadowing thex
from the outer scope. This can even be a useful idiom as new local variables are freshly created each time local scopes are entered, but this is only observable in the case of variables that outlive their scope via closures. Alet
variable without an assignment, such asvar2
in the example above, declares a new local variable that is not yet bound to a value.
By contrast,begin
blocks also group multiple expressions together but do not introduce scope or have the special assignment syntax.
Examples
In the function below, there is a singlex
that is iteratively updated three times by themap
. The closures returned all reference that onex
at its final value:
julia> function test_outer_x() x = 0 map(1:3) do _ x += 1 return ()->x end endtest_outer_x (generic function with 1 method)julia> [f() for f in test_outer_x()]3-element Vector{Int64}: 3 3 3
If, however, we add alet
block that introduces anew local variable we will end up with three distinct variables being captured (one at each iteration) even though we chose to use (shadow) the same name.
julia> function test_let_x() x = 0 map(1:3) do _ x += 1 let x = x return ()->x end end endtest_let_x (generic function with 1 method)julia> [f() for f in test_let_x()]3-element Vector{Int64}: 1 2 3
All scope constructs that introduce new local variables behave this way when repeatedly run; the distinctive feature oflet
is its ability to succinctly declare newlocal
s that may shadow outer variables of the same name. For example, directly using the argument of thedo
function similarly captures three distinct variables:
julia> function test_do_x() map(1:3) do x return ()->x end endtest_do_x (generic function with 1 method)julia> [f() for f in test_do_x()]3-element Vector{Int64}: 1 2 3
if
—Keywordif/elseif/else
if
/elseif
/else
performs conditional evaluation, which allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of theif
/elseif
/else
conditional syntax:
if x < y println("x is less than y")elseif x > y println("x is greater than y")else println("x is equal to y")end
If the condition expressionx < y
is true, then the corresponding block is evaluated; otherwise the condition expressionx > y
is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, theelse
block is evaluated. Theelseif
andelse
blocks are optional, and as manyelseif
blocks as desired can be used.
In contrast to some other languages conditions must be of typeBool
. It does not suffice for conditions to be convertible toBool
.
julia> if 1 endERROR: TypeError: non-boolean (Int64) used in boolean context
for
—Keywordfor
for
loops repeatedly evaluate a block of statements while iterating over a sequence of values.
The iteration variable is always a new variable, even if a variable of the same name exists in the enclosing scope. Useouter
to reuse an existing local variable for iteration.
Examples
julia> for i in [1, 4, 0] println(i) end140
while
—Keywordwhile
while
loops repeatedly evaluate a conditional expression, and continue evaluating the body of the while loop as long as the expression remains true. If the condition expression is false when the while loop is first reached, the body is never evaluated.
Examples
julia> i = 11julia> while i < 5 println(i) global i += 1 end1234
break
—Keywordbreak
Break out of a loop immediately.
Examples
julia> i = 00julia> while true global i += 1 i > 5 && break println(i) end12345
continue
—Keywordcontinue
Skip the rest of the current loop iteration.
Examples
julia> for i = 1:6 iseven(i) && continue println(i) end135
try
—Keywordtry/catch
Atry
/catch
statement allows intercepting errors (exceptions) thrown bythrow
so that program execution can continue. For example, the following code attempts to write a file, but warns the user and proceeds instead of terminating execution if the file cannot be written:
try open("/danger", "w") do f println(f, "Hello") endcatch @warn "Could not write file."end
or, when the file cannot be read into a variable:
lines = try open("/danger", "r") do f readlines(f) endcatch @warn "File not found."end
The syntaxcatch e
(wheree
is any variable) assigns the thrown exception object to the given variable within thecatch
block.
The power of thetry
/catch
construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions.
finally
—Keywordfinally
Run some code when a given block of code exits, regardless of how it exits. For example, here is how we can guarantee that an opened file is closed:
f = open("file")try operate_on_file(f)finally close(f)end
When control leaves thetry
block (for example, due to areturn
, or just finishing normally),close(f)
will be executed. If thetry
block exits due to an exception, the exception will continue propagating. Acatch
block may be combined withtry
andfinally
as well. In this case thefinally
block will run aftercatch
has handled the error.
quote
—Keywordquote
quote
creates multiple expression objects in a block without using the explicitExpr
constructor. For example:
ex = quote x = 1 y = 2 x + yend
Unlike the other means of quoting,:( ... )
, this form introducesQuoteNode
elements to the expression tree, which must be considered when directly manipulating the tree. For other purposes,:( ... )
andquote .. end
blocks are treated identically.
local
—Keywordlocal
local
introduces a new local variable. See themanual section on variable scoping for more information.
Examples
julia> function foo(n) x = 0 for i = 1:n local x # introduce a loop-local x x = i end x endfoo (generic function with 1 method)julia> foo(10)0
global
—Keywordglobal
global x
makesx
in the current scope and its inner scopes refer to the global variable of that name. See themanual section on variable scoping for more information.
Examples
julia> z = 33julia> function foo() global z = 6 # use the z variable defined outside foo endfoo (generic function with 1 method)julia> foo()6julia> z6
outer
—Keywordfor outer
Reuse an existing local variable for iteration in afor
loop.
See themanual section on variable scoping for more information.
See alsofor
.
Examples
julia> function f() i = 0 for i = 1:3 # empty end return i end;julia> f()0
julia> function f() i = 0 for outer i = 1:3 # empty end return i end;julia> f()3
julia> i = 0 # global variable for outer i = 1:3 endERROR: syntax: no outer local variable declaration exists for "for outer"[...]
const
—Keywordconst
const
is used to declare global variables whose values will not change. In almost all code (and particularly performance sensitive code) global variables should be declared constant in this way.
const x = 5
Multiple variables can be declared within a singleconst
:
const y, z = 7, 11
Note thatconst
only applies to one=
operation, thereforeconst x = y = 1
declaresx
to be constant but noty
. On the other hand,const x = const y = 1
declares bothx
andy
constant.
Note that "constant-ness" does not extend into mutable containers; only the association between a variable and its value is constant. Ifx
is an array or dictionary (for example) you can still modify, add, or remove elements.
In some cases changing the value of aconst
variable gives a warning instead of an error. However, this can produce unpredictable behavior or corrupt the state of your program, and so should be avoided. This feature is intended only for convenience during interactive use.
struct
—Keywordstruct
The most commonly used kind of type in Julia is a struct, specified as a name and a set of fields.
struct Point x yend
Fields can have type restrictions, which may be parameterized:
struct Point{X} x::X y::Float64end
A struct can also declare an abstract super type via<:
syntax:
struct Point <: AbstractPoint x yend
struct
s are immutable by default; an instance of one of these types cannot be modified after construction. Usemutable struct
instead to declare a type whose instances can be modified.
See the manual section onComposite Types for more details, such as how to define constructors.
mutable struct
—Keywordmutable struct
mutable struct
is similar tostruct
, but additionally allows the fields of the type to be set after construction.
Individual fields of a mutable struct can be marked asconst
to make them immutable:
mutable struct Baz a::Int const b::Float64end
Theconst
keyword for fields of mutable structs requires at least Julia 1.8.
See the manual section onComposite Types for more information.
Base.@kwdef
—Macro@kwdef typedef
This is a helper macro that automatically defines a keyword-based constructor for the type declared in the expressiontypedef
, which must be astruct
ormutable struct
expression. The default argument is supplied by declaring fields of the formfield::T = default
orfield = default
. If no default is provided then the keyword argument becomes a required keyword argument in the resulting type constructor.
Inner constructors can still be defined, but at least one should accept arguments in the same form as the default inner constructor (i.e. one positional argument per field) in order to function correctly with the keyword outer constructor.
Base.@kwdef
for parametric structs, and structs with supertypes requires at least Julia 1.1.
This macro is exported as of Julia 1.9.
Examples
julia> @kwdef struct Foo a::Int = 1 # specified default b::String # required keyword endFoojulia> Foo(b="hi")Foo(1, "hi")julia> Foo()ERROR: UndefKeywordError: keyword argument `b` not assignedStacktrace:[...]
abstract type
—Keywordabstract type
abstract type
declares a type that cannot be instantiated, and serves only as a node in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. Abstract types form the conceptual hierarchy which makes Julia’s type system more than just a collection of object implementations. For example:
abstract type Number endabstract type Real <: Number end
Number
has no supertype, whereasReal
is an abstract subtype ofNumber
.
primitive type
—Keywordprimitive type
primitive type
declares a concrete type whose data consists only of a series of bits. Classic examples of primitive types are integers and floating-point values. Some example built-in primitive type declarations:
primitive type Char 32 endprimitive type Bool <: Integer 8 end
The number after the name indicates how many bits of storage the type requires. Currently, only sizes that are multiples of 8 bits are supported. TheBool
declaration shows how a primitive type can be optionally declared to be a subtype of some supertype.
where
—Keywordwhere
Thewhere
keyword creates aUnionAll
type, which may be thought of as an iterated union of other types, over all values of some variable. For exampleVector{T} where T<:Real
includes allVector
s where the element type is some kind ofReal
number.
The variable bound defaults toAny
if it is omitted:
Vector{T} where T # short for `where T<:Any`
Variables can also have lower bounds:
Vector{T} where T>:IntVector{T} where Int<:T<:Real
There is also a concise syntax for nestedwhere
expressions. For example, this:
Pair{T, S} where S<:Array{T} where T<:Number
can be shortened to:
Pair{T, S} where {T<:Number, S<:Array{T}}
This form is often found on method signatures.
Note that in this form, the variables are listed outermost-first. This matches the order in which variables are substituted when a type is "applied" to parameter values using the syntaxT{p1, p2, ...}
.
...
—Keyword...
The "splat" operator,...
, represents a sequence of arguments....
can be used in function definitions, to indicate that the function accepts an arbitrary number of arguments....
can also be used to apply a function to a sequence of arguments.
Examples
julia> add(xs...) = reduce(+, xs)add (generic function with 1 method)julia> add(1, 2, 3, 4, 5)15julia> add([1, 2, 3]...)6julia> add(7, 1:100..., 1000:1100...)111107
;
—Keyword;
;
has a similar role in Julia as in many C-like languages, and is used to delimit the end of the previous statement.
;
is not necessary at the end of a line, but can be used to separate statements on a single line or to join statements into a single expression.
Adding;
at the end of a line in the REPL will suppress printing the result of that expression.
In function declarations, and optionally in calls,;
separates regular arguments from keywords.
In array literals, arguments separated by semicolons have their contents concatenated together. A separator made of a single;
concatenates vertically (i.e. along the first dimension),;;
concatenates horizontally (second dimension),;;;
concatenates along the third dimension, etc. Such a separator can also be used in last position in the square brackets to add trailing dimensions of length 1.
A;
in first position inside of parentheses can be used to construct a named tuple. The same(; ...)
syntax on the left side of an assignment allows for property destructuring.
In the standard REPL, typing;
on an empty line will switch to shell mode.
Examples
julia> function foo() x = "Hello, "; x *= "World!" return x endfoo (generic function with 1 method)julia> bar() = (x = "Hello, Mars!"; return x)bar (generic function with 1 method)julia> foo();julia> bar()"Hello, Mars!"julia> function plot(x, y; style="solid", width=1, color="black") ### endjulia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> [1; 3;; 2; 4;;; 10*A]2×2×2 Array{Int64, 3}:[:, :, 1] = 1 2 3 4[:, :, 2] = 10 20 30 40julia> [2; 3;;;]2×1×1 Array{Int64, 3}:[:, :, 1] = 2 3julia> nt = (; x=1) # without the ; or a trailing comma this would assign to x(x = 1,)julia> key = :a; c = 3;julia> nt2 = (; key => 1, b=2, c, nt.x)(a = 1, b = 2, c = 3, x = 1)julia> (; b, x) = nt2; # set variables b and x using property destructuringjulia> b, x(2, 1)julia> ; # upon typing ;, the prompt changes (in place) to: shell>shell> echo hellohello
=
—Keyword=
=
is the assignment operator.
a
and expressionb
,a = b
makesa
refer to the value ofb
.f(x)
,f(x) = x
defines a new function constantf
, or adds a new method tof
iff
is already defined; this usage is equivalent tofunction f(x); x; end
.a[i] = v
callssetindex!
(a,v,i)
.a.b = c
callssetproperty!
(a,:b,c)
.f(a=b)
passesb
as the value of keyword argumenta
.(a=1,)
constructs aNamedTuple
.Examples
Assigninga
tob
does not create a copy ofb
; instead usecopy
ordeepcopy
.
julia> b = [1]; a = b; b[1] = 2; a1-element Array{Int64, 1}: 2julia> b = [1]; a = copy(b); b[1] = 2; a1-element Array{Int64, 1}: 1
Collections passed to functions are also not copied. Functions can modify (mutate) the contents of the objects their arguments refer to. (The names of functions which do this are conventionally suffixed with '!'.)
julia> function f!(x); x[:] .+= 1; endf! (generic function with 1 method)julia> a = [1]; f!(a); a1-element Array{Int64, 1}: 2
Assignment can operate on multiple variables in parallel, taking values from an iterable:
julia> a, b = 4, 5(4, 5)julia> a, b = 1:31:3julia> a, b(1, 2)
Assignment can operate on multiple variables in series, and will return the value of the right-hand-most expression:
julia> a = [1]; b = [2]; c = [3]; a = b = c1-element Array{Int64, 1}: 3julia> b[1] = 2; a, b, c([2], [2], [2])
Assignment at out-of-bounds indices does not grow a collection. If the collection is aVector
it can instead be grown withpush!
orappend!
.
julia> a = [1, 1]; a[3] = 2ERROR: BoundsError: attempt to access 2-element Array{Int64, 1} at index [3][...]julia> push!(a, 2, 3)4-element Array{Int64, 1}: 1 1 2 3
Assigning[]
does not eliminate elements from a collection; instead usefilter!
.
julia> a = collect(1:3); a[a .<= 1] = []ERROR: DimensionMismatch: tried to assign 0 elements to 1 destinations[...]julia> filter!(x -> x > 1, a) # in-place & thus more efficient than a = a[a .> 1]2-element Array{Int64, 1}: 2 3
?:
—Keyworda ? b : c
Short form for conditionals; read "ifa
, evaluateb
otherwise evaluatec
". Also known as theternary operator.
This syntax is equivalent toif a; b else c end
, but is often used to emphasize the valueb
-or-c
which is being used as part of a larger expression, rather than the side effects that evaluatingb
orc
may have.
See the manual section oncontrol flow for more details.
Examples
julia> x = 1; y = 2;julia> x > y ? println("x is larger") : println("x is not larger")x is not largerjulia> x > y ? "x is larger" : x == y ? "x and y are equal" : "y is larger""y is larger"
Main
—ModuleMain
Main
is the top-level module, and Julia starts withMain
set as the current module. Variables defined at the prompt go inMain
, andvarinfo
lists variables inMain
.
julia> @__MODULE__Main
Core
—ModuleCore
Core
is the module that contains all identifiers considered "built in" to the language, i.e. part of the core language and not libraries. Every module implicitly specifiesusing Core
, since you can't do anything without those definitions.
Base
—ModuleBase
The base library of Julia.Base
is a module that contains basic functionality (the contents ofbase/
). All modules implicitly containusing Base
, since this is needed in the vast majority of cases.
Base.Broadcast
—ModuleBase.Broadcast
Module containing the broadcasting implementation.
Base.Docs
—ModuleDocs
TheDocs
module provides the@doc
macro which can be used to set and retrieve documentation metadata for Julia objects.
Please see the manual section ondocumentation for more information.
Base.Iterators
—ModuleMethods for working with Iterators.
Base.Libc
—ModuleInterface to libc, the C standard library.
Base.Meta
—ModuleConvenience functions for metaprogramming.
Base.StackTraces
—ModuleTools for collecting and manipulating stack traces. Mainly used for building errors.
Base.Sys
—ModuleProvide methods for retrieving information about hardware and the operating system.
Base.Threads
—ModuleMultithreading support.
Base.GC
—ModuleBase.GC
Module with garbage collection utilities.
Core.:===
—Function===(x,y) -> Bool≡(x,y) -> Bool
Determine whetherx
andy
are identical, in the sense that no program could distinguish them. First the types ofx
andy
are compared. If those are identical, mutable objects are compared by address in memory and immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes called "egal". It always returns aBool
value.
Examples
julia> a = [1, 2]; b = [1, 2];julia> a == btruejulia> a === bfalsejulia> a === atrue
Core.isa
—Functionisa(x, type) -> Bool
Determine whetherx
is of the giventype
. Can also be used as an infix operator, e.g.x isa type
.
Examples
julia> isa(1, Int)truejulia> isa(1, Matrix)falsejulia> isa(1, Char)falsejulia> isa(1, Number)truejulia> 1 isa Numbertrue
Base.isequal
—Functionisequal(x, y) -> Bool
Similar to==
, except for the treatment of floating point numbers and of missing values.isequal
treats all floating-pointNaN
values as equal to each other, treats-0.0
as unequal to0.0
, andmissing
as equal tomissing
. Always returns aBool
value.
isequal
is an equivalence relation - it is reflexive (===
impliesisequal
), symmetric (isequal(a, b)
impliesisequal(b, a)
) and transitive (isequal(a, b)
andisequal(b, c)
impliesisequal(a, c)
).
Implementation
The default implementation ofisequal
calls==
, so a type that does not involve floating-point values generally only needs to define==
.
isequal
is the comparison function used by hash tables (Dict
).isequal(x,y)
must imply thathash(x) == hash(y)
.
This typically means that types for which a custom==
orisequal
method exists must implement a correspondinghash
method (and vice versa). Collections typically implementisequal
by callingisequal
recursively on all contents.
Furthermore,isequal
is linked withisless
, and they work together to define a fixed total ordering, where exactly one ofisequal(x, y)
,isless(x, y)
, orisless(y, x)
must betrue
(and the other twofalse
).
Scalar types generally do not need to implementisequal
separate from==
, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based onisnan
,signbit
, and==
).
Examples
julia> isequal([1., NaN], [1., NaN])truejulia> [1., NaN] == [1., NaN]falsejulia> 0.0 == -0.0truejulia> isequal(0.0, -0.0)falsejulia> missing == missingmissingjulia> isequal(missing, missing)true
isequal(x)
Create a function that compares its argument tox
usingisequal
, i.e. a function equivalent toy -> isequal(y, x)
.
The returned function is of typeBase.Fix2{typeof(isequal)}
, which can be used to implement specialized methods.
Base.isless
—Functionisless(x, y)
Test whetherx
is less thany
, according to a fixed total order (defined together withisequal
).isless
is not defined for pairs(x, y)
of all types. However, if it is defined, it is expected to satisfy the following:
isless(x, y)
is defined, then so isisless(y, x)
andisequal(x, y)
, and exactly one of those three yieldstrue
.isless
is transitive, i.e.,isless(x, y) && isless(y, z)
impliesisless(x, z)
.Values that are normally unordered, such asNaN
, are ordered after regular values.missing
values are ordered last.
This is the default comparison used bysort!
.
Implementation
Non-numeric types with a total order should implement this function. Numeric types only need to implement it if they have special values such asNaN
. Types with a partial order should implement<
. See the documentation onAlternate Orderings for how to define alternate ordering methods that can be used in sorting and related functions.
Examples
julia> isless(1, 3)truejulia> isless("Red", "Blue")false
Base.isunordered
—Functionisunordered(x)
Returntrue
ifx
is a value that is not orderable according to<
, such asNaN
ormissing
.
The values that evaluate totrue
with this predicate may be orderable with respect to other orderings such asisless
.
This function requires Julia 1.7 or later.
Base.ifelse
—Functionifelse(condition::Bool, x, y)
Returnx
ifcondition
istrue
, otherwise returny
. This differs from?
orif
in that it is an ordinary function, so all the arguments are evaluated first. In some cases, usingifelse
instead of anif
statement can eliminate the branch in generated code and provide higher performance in tight loops.
Examples
julia> ifelse(1 > 2, 1, 2)2
Core.typeassert
—Functiontypeassert(x, type)
Throw aTypeError
unlessx isa type
. The syntaxx::type
calls this function.
Examples
julia> typeassert(2.5, Int)ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64Stacktrace:[...]
Core.typeof
—Functiontypeof(x)
Get the concrete type ofx
.
See alsoeltype
.
Examples
julia> a = 1//2;julia> typeof(a)Rational{Int64}julia> M = [1 2; 3.5 4];julia> typeof(M)Matrix{Float64} (alias for Array{Float64, 2})
Core.tuple
—Functiontuple(xs...)
Construct a tuple of the given objects.
See alsoTuple
,ntuple
,NamedTuple
.
Examples
julia> tuple(1, 'b', pi)(1, 'b', π)julia> ans === (1, 'b', π)truejulia> Tuple(Real[1, 2, pi]) # takes a collection(1, 2, π)
Base.ntuple
—Functionntuple(f, n::Integer)
Create a tuple of lengthn
, computing each element asf(i)
, wherei
is the index of the element.
Examples
julia> ntuple(i -> 2*i, 4)(2, 4, 6, 8)
ntuple(f, ::Val{N})
Create a tuple of lengthN
, computing each element asf(i)
, wherei
is the index of the element. By taking aVal(N)
argument, it is possible that this version of ntuple may generate more efficient code than the version taking the length as an integer. Butntuple(f, N)
is preferable tontuple(f, Val(N))
in cases whereN
cannot be determined at compile time.
Examples
julia> ntuple(i -> 2*i, Val(4))(2, 4, 6, 8)
Base.objectid
—Functionobjectid(x) -> UInt
Get a hash value forx
based on object identity.
Ifx === y
thenobjectid(x) == objectid(y)
, and usually whenx !== y
,objectid(x) != objectid(y)
.
Base.hash
—Functionhash(x[, h::UInt]) -> UInt
Compute an integer hash code such thatisequal(x,y)
implieshash(x)==hash(y)
. The optional second argumenth
is another hash code to be mixed with the result.
New types should implement the 2-argument form, typically by calling the 2-argumenthash
method recursively in order to mix hashes of the contents with each other (and withh
). Typically, any type that implementshash
should also implement its own==
(henceisequal
) to guarantee the property mentioned above.
The hash value may change when a new Julia process is started.
julia> a = hash(10)0x95ea2955abd45275julia> hash(10, a) # only use the output of another hash function as the second argument0xd42bad54a8575b16
Base.finalizer
—Functionfinalizer(f, x)
Register a functionf(x)
to be called when there are no program-accessible references tox
, and returnx
. The type ofx
must be amutable struct
, otherwise the function will throw.
f
must not cause a task switch, which excludes most I/O operations such asprintln
. Using the@async
macro (to defer context switching to outside of the finalizer) orccall
to directly invoke IO functions in C may be helpful for debugging purposes.
Note that there is no guaranteed world age for the execution off
. It may be called in the world age in which the finalizer was registered or any later world age.
Examples
finalizer(my_mutable_struct) do x @async println("Finalizing $x.")endfinalizer(my_mutable_struct) do x ccall(:jl_safe_printf, Cvoid, (Cstring, Cstring), "Finalizing %s.", repr(x))end
A finalizer may be registered at object construction. In the following example note that we implicitly rely on the finalizer returning the newly created mutable structx
.
mutable struct MyMutableStruct bar function MyMutableStruct(bar) x = new(bar) f(t) = @async println("Finalizing $t.") finalizer(f, x) endend
Base.finalize
—Functionfinalize(x)
Immediately run finalizers registered for objectx
.
Base.copy
—Functioncopy(x)
Create a shallow copy ofx
: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.
Base.deepcopy
—Functiondeepcopy(x)
Create a deep copy ofx
: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array creates deep copies of all the objects it contains and produces a new array with the consistent relationship structure (e.g., if the first two elements are the same object in the original array, the first two elements of the new array will also be the samedeepcopy
ed object). Callingdeepcopy
on an object should generally have the same effect as serializing and then deserializing it.
While it isn't normally necessary, user-defined types can override the defaultdeepcopy
behavior by defining a specialized version of the functiondeepcopy_internal(x::T, dict::IdDict)
(which shouldn't otherwise be used), whereT
is the type to be specialized for, anddict
keeps track of objects copied so far within the recursion. Within the definition,deepcopy_internal
should be used in place ofdeepcopy
, and thedict
variable should be updated as appropriate before returning.
Base.getproperty
—Functiongetproperty(value, name::Symbol)getproperty(value, name::Symbol, order::Symbol)
The syntaxa.b
callsgetproperty(a, :b)
. The syntax@atomic order a.b
callsgetproperty(a, :b, :order)
and the syntax@atomic a.b
callsgetproperty(a, :b, :sequentially_consistent)
.
Examples
julia> struct MyType{T <: Number} x::T endjulia> function Base.getproperty(obj::MyType, sym::Symbol) if sym === :special return obj.x + 1 else # fallback to getfield return getfield(obj, sym) end endjulia> obj = MyType(1);julia> obj.special2julia> obj.x1
One should overloadgetproperty
only when necessary, as it can be confusing if the behavior of the syntaxobj.f
is unusual. Also note that using methods is often preferable. See also this style guide documentation for more information:Prefer exported methods over direct field access.
See alsogetfield
,propertynames
andsetproperty!
.
Base.setproperty!
—Functionsetproperty!(value, name::Symbol, x)setproperty!(value, name::Symbol, x, order::Symbol)
The syntaxa.b = c
callssetproperty!(a, :b, c)
. The syntax@atomic order a.b = c
callssetproperty!(a, :b, c, :order)
and the syntax@atomic a.b = c
callssetproperty!(a, :b, c, :sequentially_consistent)
.
setproperty!
on modules requires at least Julia 1.8.
See alsosetfield!
,propertynames
andgetproperty
.
Base.replaceproperty!
—Functionreplaceproperty!(x, f::Symbol, expected, desired, success_order::Symbol=:not_atomic, fail_order::Symbol=success_order)
Perform a compare-and-swap operation onx.f
fromexpected
todesired
, per egal. The syntax@atomicreplace x.f expected => desired
can be used instead of the function call form.
Base.swapproperty!
—Functionswapproperty!(x, f::Symbol, v, order::Symbol=:not_atomic)
The syntax@atomic a.b, _ = c, a.b
returns(c, swapproperty!(a, :b, c, :sequentially_consistent))
, where there must be onegetproperty
expression common to both sides.
See alsoswapfield!
andsetproperty!
.
Base.modifyproperty!
—Functionmodifyproperty!(x, f::Symbol, op, v, order::Symbol=:not_atomic)
The syntax@atomic op(x.f, v)
(and its equivalent@atomic x.f op v
) returnsmodifyproperty!(x, :f, op, v, :sequentially_consistent)
, where the first argument must be agetproperty
expression and is modified atomically.
Invocation ofop(getproperty(x, f), v)
must return a value that can be stored in the fieldf
of the objectx
by default. In particular, unlike the default behavior ofsetproperty!
, theconvert
function is not called automatically.
See alsomodifyfield!
andsetproperty!
.
Base.setpropertyonce!
—Functionsetpropertyonce!(x, f::Symbol, value, success_order::Symbol=:not_atomic, fail_order::Symbol=success_order)
Perform a compare-and-swap operation onx.f
to set it tovalue
if previously unset. The syntax@atomiconce x.f = value
can be used instead of the function call form.
See alsosetfieldonce!
,setproperty!
,replaceproperty!
.
This function requires Julia 1.11 or later.
Base.propertynames
—Functionpropertynames(x, private=false)
Get a tuple or a vector of the properties (x.property
) of an objectx
. This is typically the same asfieldnames(typeof(x))
, but types that overloadgetproperty
should generally overloadpropertynames
as well to get the properties of an instance of the type.
propertynames(x)
may return only "public" property names that are part of the documented interface ofx
. If you want it to also return "private" property names intended for internal use, passtrue
for the optional second argument. REPL tab completion onx.
shows only theprivate=false
properties.
See also:hasproperty
,hasfield
.
Base.hasproperty
—Functionhasproperty(x, s::Symbol)
Return a boolean indicating whether the objectx
hass
as one of its own properties.
This function requires at least Julia 1.2.
See also:propertynames
,hasfield
.
Core.getfield
—Functiongetfield(value, name::Symbol, [order::Symbol])getfield(value, i::Int, [order::Symbol])
Extract a field from a compositevalue
by name or position. Optionally, an ordering can be defined for the operation. If the field was declared@atomic
, the specification is strongly recommended to be compatible with the stores to that location. Otherwise, if not declared as@atomic
, this parameter must be:not_atomic
if specified. See alsogetproperty
andfieldnames
.
Examples
julia> a = 1//21//2julia> getfield(a, :num)1julia> a.num1julia> getfield(a, 1)1
Core.setfield!
—Functionsetfield!(value, name::Symbol, x, [order::Symbol])setfield!(value, i::Int, x, [order::Symbol])
Assignx
to a named field invalue
of composite type. Thevalue
must be mutable andx
must be a subtype offieldtype(typeof(value), name)
. Additionally, an ordering can be specified for this operation. If the field was declared@atomic
, this specification is mandatory. Otherwise, if not declared as@atomic
, it must be:not_atomic
if specified. See alsosetproperty!
.
Examples
julia> mutable struct MyMutableStruct field::Int endjulia> a = MyMutableStruct(1);julia> setfield!(a, :field, 2);julia> getfield(a, :field)2julia> a = 1//21//2julia> setfield!(a, :num, 3);ERROR: setfield!: immutable struct of type Rational cannot be changed
Core.modifyfield!
—Functionmodifyfield!(value, name::Symbol, op, x, [order::Symbol]) -> Pairmodifyfield!(value, i::Int, op, x, [order::Symbol]) -> Pair
Atomically perform the operations to get and set a field after applying the functionop
.
y = getfield(value, name)z = op(y, x)setfield!(value, name, z)return y => z
If supported by the hardware (for example, atomic increment), this may be optimized to the appropriate hardware instruction, otherwise it'll use a loop.
This function requires Julia 1.7 or later.
Core.replacefield!
—Functionreplacefield!(value, name::Symbol, expected, desired, [success_order::Symbol, [fail_order::Symbol=success_order]) -> (; old, success::Bool)replacefield!(value, i::Int, expected, desired, [success_order::Symbol, [fail_order::Symbol=success_order]) -> (; old, success::Bool)
Atomically perform the operations to get and conditionally set a field to a given value.
y = getfield(value, name, fail_order)ok = y === expectedif ok setfield!(value, name, desired, success_order)endreturn (; old = y, success = ok)
If supported by the hardware, this may be optimized to the appropriate hardware instruction, otherwise it'll use a loop.
This function requires Julia 1.7 or later.
Core.swapfield!
—Functionswapfield!(value, name::Symbol, x, [order::Symbol])swapfield!(value, i::Int, x, [order::Symbol])
Atomically perform the operations to simultaneously get and set a field:
y = getfield(value, name)setfield!(value, name, x)return y
This function requires Julia 1.7 or later.
Core.setfieldonce!
—Functionsetfieldonce!(value, name::Union{Int,Symbol}, desired, [success_order::Symbol, [fail_order::Symbol=success_order]) -> success::Bool
Atomically perform the operations to set a field to a given value, only if it was previously not set.
ok = !isdefined(value, name, fail_order)if ok setfield!(value, name, desired, success_order)endreturn ok
This function requires Julia 1.11 or later.
Core.isdefined
—Functionisdefined(m::Module, s::Symbol, [order::Symbol])isdefined(object, s::Symbol, [order::Symbol])isdefined(object, index::Int, [order::Symbol])
Tests whether a global variable or object field is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index. Optionally, an ordering can be defined for the operation. If the field was declared@atomic
, the specification is strongly recommended to be compatible with the stores to that location. Otherwise, if not declared as@atomic
, this parameter must be:not_atomic
if specified.
To test whether an array element is defined, useisassigned
instead.
See also@isdefined
.
Examples
julia> isdefined(Base, :sum)truejulia> isdefined(Base, :NonExistentMethod)falsejulia> a = 1//2;julia> isdefined(a, 2)truejulia> isdefined(a, 3)falsejulia> isdefined(a, :num)truejulia> isdefined(a, :numerator)false
Base.@isdefined
—Macro@isdefined s -> Bool
Tests whether variables
is defined in the current scope.
See alsoisdefined
for field properties andisassigned
for array indexes orhaskey
for other mappings.
Examples
julia> @isdefined newvarfalsejulia> newvar = 11julia> @isdefined newvartruejulia> function f() println(@isdefined x) x = 3 println(@isdefined x) endf (generic function with 1 method)julia> f()falsetrue
Base.convert
—Functionconvert(T, x)
Convertx
to a value of typeT
.
IfT
is anInteger
type, anInexactError
will be raised ifx
is not representable byT
, for example ifx
is not integer-valued, or is outside the range supported byT
.
Examples
julia> convert(Int, 3.0)3julia> convert(Int, 3.5)ERROR: InexactError: Int64(3.5)Stacktrace:[...]
IfT
is aAbstractFloat
type, then it will return the closest value tox
representable byT
. Inf is treated as one ulp greater thanfloatmax(T)
for purposes of determining nearest.
julia> x = 1/30.3333333333333333julia> convert(Float32, x)0.33333334f0julia> convert(BigFloat, x)0.333333333333333314829616256247390992939472198486328125
IfT
is a collection type andx
a collection, the result ofconvert(T, x)
may alias all or part ofx
.
julia> x = Int[1, 2, 3];julia> y = convert(Vector{Int}, x);julia> y === xtrue
See also:round
,trunc
,oftype
,reinterpret
.
Base.promote
—Functionpromote(xs...)
Convert all arguments to a common type, and return them all (as a tuple). If no arguments can be converted, an error is raised.
See also:promote_type
,promote_rule
.
Examples
julia> promote(Int8(1), Float16(4.5), Float32(4.1))(1.0f0, 4.5f0, 4.1f0)julia> promote_type(Int8, Float16, Float32)Float32julia> reduce(Base.promote_typejoin, (Int8, Float16, Float32))Realjulia> promote(1, "x")ERROR: promotion of types Int64 and String failed to change any arguments[...]julia> promote_type(Int, String)Any
Base.oftype
—Functionoftype(x, y)
Converty
to the type ofx
i.e.convert(typeof(x), y)
.
Examples
julia> x = 4;julia> y = 3.;julia> oftype(x, y)3julia> oftype(y, x)4.0
Base.widen
—Functionwiden(x)
Ifx
is a type, return a "larger" type, defined so that arithmetic operations+
and-
are guaranteed not to overflow nor lose precision for any combination of values that typex
can hold.
For fixed-size integer types less than 128 bits,widen
will return a type with twice the number of bits.
Ifx
is a value, it is converted towiden(typeof(x))
.
Examples
julia> widen(Int32)Int64julia> widen(1.5f0)1.5
Base.identity
—Functionidentity(x)
The identity function. Returns its argument.
See also:one
,oneunit
, andLinearAlgebra
'sI
.
Examples
julia> identity("Well, what did you expect?")"Well, what did you expect?"
Core.WeakRef
—TypeWeakRef(x)
w = WeakRef(x)
constructs aweak reference to the Julia valuex
: althoughw
contains a reference tox
, it does not preventx
from being garbage collected.w.value
is eitherx
(ifx
has not been garbage-collected yet) ornothing
(ifx
has been garbage-collected).
julia> x = "a string""a string"julia> w = WeakRef(x)WeakRef("a string")julia> GC.gc()julia> w # a reference is maintained via `x`WeakRef("a string")julia> x = nothing # clear referencejulia> GC.gc()julia> wWeakRef(nothing)
Base.supertype
—Functionsupertype(T::DataType)
Return the supertype of DataTypeT
.
Examples
julia> supertype(Int32)Signed
Core.Type
—TypeCore.Type{T}
Core.Type
is an abstract type which has all type objects as its instances. The only instance of the singleton typeCore.Type{T}
is the objectT
.
Examples
julia> isa(Type{Float64}, Type)truejulia> isa(Float64, Type)truejulia> isa(Real, Type{Float64})falsejulia> isa(Real, Type{Real})true
Core.DataType
—TypeDataType <: Type{T}
DataType
represents explicitly declared types that have names, explicitly declared supertypes, and, optionally, parameters. Every concrete value in the system is an instance of someDataType
.
Examples
julia> typeof(Real)DataTypejulia> typeof(Int)DataTypejulia> struct Point x::Int y endjulia> typeof(Point)DataType
Core.:<:
—Function<:(T1, T2)
Subtype operator: returnstrue
if and only if all values of typeT1
are also of typeT2
.
Examples
julia> Float64 <: AbstractFloattruejulia> Vector{Int} <: AbstractArraytruejulia> Matrix{Float64} <: Matrix{AbstractFloat}false
Base.:>:
—Function>:(T1, T2)
Supertype operator, equivalent toT2 <: T1
.
Base.typejoin
—Functiontypejoin(T, S, ...)
Return the closest common ancestor of typesT
andS
, i.e. the narrowest type from which they both inherit. Recurses on additional varargs.
Examples
julia> typejoin(Int, Float64)Realjulia> typejoin(Int, Float64, ComplexF32)Number
Base.typeintersect
—Functiontypeintersect(T::Type, S::Type)
Compute a type that contains the intersection ofT
andS
. Usually this will be the smallest such type or one close to it.
A special case where exact behavior is guaranteed: whenT <: S
,typeintersect(S, T) == T == typeintersect(T, S)
.
Base.promote_type
—Functionpromote_type(type1, type2, ...)
Promotion refers to converting values of mixed types to a single common type.promote_type
represents the default promotion behavior in Julia when operators (usually mathematical) are given arguments of differing types.promote_type
generally tries to return a type which can at least approximate most values of either input type without excessively widening. Some loss is tolerated; for example,promote_type(Int64, Float64)
returnsFloat64
even though strictly, not allInt64
values can be represented exactly asFloat64
values.
See also:promote
,promote_typejoin
,promote_rule
.
Examples
julia> promote_type(Int64, Float64)Float64julia> promote_type(Int32, Int64)Int64julia> promote_type(Float32, BigInt)BigFloatjulia> promote_type(Int16, Float16)Float16julia> promote_type(Int64, Float16)Float16julia> promote_type(Int8, UInt16)UInt16
To overload promotion for your own types you should overloadpromote_rule
.promote_type
callspromote_rule
internally to determine the type. Overloadingpromote_type
directly can cause ambiguity errors.
Base.promote_rule
—Functionpromote_rule(type1, type2)
Specifies what type should be used bypromote
when given values of typestype1
andtype2
. This function should not be called directly, but should have definitions added to it for new types as appropriate.
Base.promote_typejoin
—Functionpromote_typejoin(T, S)
Compute a type that contains bothT
andS
, which could be either a parent of both types, or aUnion
if appropriate. Falls back totypejoin
.
See insteadpromote
,promote_type
.
Examples
julia> Base.promote_typejoin(Int, Float64)Realjulia> Base.promote_type(Int, Float64)Float64
Base.isdispatchtuple
—Functionisdispatchtuple(T)
Determine whether typeT
is a tuple "leaf type", meaning it could appear as a type signature in dispatch and has no subtypes (or supertypes) which could appear in a call. IfT
is not a type, then returnfalse
.
Base.ismutable
—Functionismutable(v) -> Bool
Returntrue
if and only if valuev
is mutable. SeeMutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it aDataType
, it will tell you that a value of the type is mutable.
For technical reasons,ismutable
returnstrue
for values of certain special types (for exampleString
andSymbol
) even though they cannot be mutated in a permissible way.
See alsoisbits
,isstructtype
.
Examples
julia> ismutable(1)falsejulia> ismutable([1,2])true
This function requires at least Julia 1.5.
Base.isimmutable
—Functionisimmutable(v) -> Bool
Consider using!ismutable(v)
instead, asisimmutable(v)
will be replaced by!ismutable(v)
in a future release. (Since Julia 1.5)
Returntrue
iff valuev
is immutable. SeeMutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value ofDataType
is mutable.
Examples
julia> isimmutable(1)truejulia> isimmutable([1,2])false
Base.ismutabletype
—Functionismutabletype(T) -> Bool
Determine whether typeT
was declared as a mutable type (i.e. usingmutable struct
keyword). IfT
is not a type, then returnfalse
.
This function requires at least Julia 1.7.
Base.isabstracttype
—Functionisabstracttype(T)
Determine whether typeT
was declared as an abstract type (i.e. using theabstract type
syntax). Note that this is not the negation ofisconcretetype(T)
. IfT
is not a type, then returnfalse
.
Examples
julia> isabstracttype(AbstractArray)truejulia> isabstracttype(Vector)false
Base.isprimitivetype
—Functionisprimitivetype(T) -> Bool
Determine whether typeT
was declared as a primitive type (i.e. using theprimitive type
syntax). IfT
is not a type, then returnfalse
.
Base.issingletontype
—FunctionBase.issingletontype(T)
Determine whether typeT
has exactly one possible instance; for example, a struct type with no fields except other singleton values. IfT
is not a concrete type, then returnfalse
.
Base.isstructtype
—Functionisstructtype(T) -> Bool
Determine whether typeT
was declared as a struct type (i.e. using thestruct
ormutable struct
keyword). IfT
is not a type, then returnfalse
.
Base.nameof
—Methodnameof(t::DataType) -> Symbol
Get the name of a (potentiallyUnionAll
-wrapped)DataType
(without its parent module) as a symbol.
Examples
julia> module Foo struct S{T} end endFoojulia> nameof(Foo.S{T} where T):S
Base.fieldnames
—Functionfieldnames(x::DataType)
Get a tuple with the names of the fields of aDataType
.
See alsopropertynames
,hasfield
.
Examples
julia> fieldnames(Rational)(:num, :den)julia> fieldnames(typeof(1+im))(:re, :im)
Base.fieldname
—Functionfieldname(x::DataType, i::Integer)
Get the name of fieldi
of aDataType
.
Examples
julia> fieldname(Rational, 1):numjulia> fieldname(Rational, 2):den
Core.fieldtype
—Functionfieldtype(T, name::Symbol | index::Int)
Determine the declared type of a field (specified by name or index) in a composite DataTypeT
.
Examples
julia> struct Foo x::Int64 y::String endjulia> fieldtype(Foo, :x)Int64julia> fieldtype(Foo, 2)String
Base.fieldtypes
—Functionfieldtypes(T::Type)
The declared types of all fields in a composite DataTypeT
as a tuple.
This function requires at least Julia 1.1.
Examples
julia> struct Foo x::Int64 y::String endjulia> fieldtypes(Foo)(Int64, String)
Base.fieldcount
—Functionfieldcount(t::Type)
Get the number of fields that an instance of the given type would have. An error is thrown if the type is too abstract to determine this.
Base.hasfield
—Functionhasfield(T::Type, name::Symbol)
Return a boolean indicating whetherT
hasname
as one of its own fields.
See alsofieldnames
,fieldcount
,hasproperty
.
This function requires at least Julia 1.2.
Examples
julia> struct Foo bar::Int endjulia> hasfield(Foo, :bar)truejulia> hasfield(Foo, :x)false
Core.nfields
—Functionnfields(x) -> Int
Get the number of fields in the given object.
Examples
julia> a = 1//2;julia> nfields(a)2julia> b = 11julia> nfields(b)0julia> ex = ErrorException("I've done a bad thing");julia> nfields(ex)1
In these examples,a
is aRational
, which has two fields.b
is anInt
, which is a primitive bitstype with no fields at all.ex
is anErrorException
, which has one field.
Base.isconst
—Functionisconst(m::Module, s::Symbol) -> Bool
Determine whether a global is declaredconst
in a given modulem
.
isconst(t::DataType, s::Union{Int,Symbol}) -> Bool
Determine whether a fields
is declaredconst
in a given typet
.
Base.isfieldatomic
—Functionisfieldatomic(t::DataType, s::Union{Int,Symbol}) -> Bool
Determine whether a fields
is declared@atomic
in a given typet
.
Base.sizeof
—Methodsizeof(T::DataType)sizeof(obj)
Size, in bytes, of the canonical binary representation of the givenDataType
T
, if any. Or the size, in bytes, of objectobj
if it is not aDataType
.
See alsoBase.summarysize
.
Examples
julia> sizeof(Float32)4julia> sizeof(ComplexF64)16julia> sizeof(1.0)8julia> sizeof(collect(1.0:10.0))80julia> struct StructWithPadding x::Int64 flag::Bool endjulia> sizeof(StructWithPadding) # not the sum of `sizeof` of fields due to padding16julia> sizeof(Int64) + sizeof(Bool) # different from above9
IfDataType
T
does not have a specific size, an error is thrown.
julia> sizeof(AbstractArray)ERROR: Abstract type AbstractArray does not have a definite size.Stacktrace:[...]
Base.isconcretetype
—Functionisconcretetype(T)
Determine whether typeT
is a concrete type, meaning it could have direct instances (valuesx
such thattypeof(x) === T
). Note that this is not the negation ofisabstracttype(T)
. IfT
is not a type, then returnfalse
.
See also:isbits
,isabstracttype
,issingletontype
.
Examples
julia> isconcretetype(Complex)falsejulia> isconcretetype(Complex{Float32})truejulia> isconcretetype(Vector{Complex})truejulia> isconcretetype(Vector{Complex{Float32}})truejulia> isconcretetype(Union{})falsejulia> isconcretetype(Union{Int,String})false
Base.isbits
—Functionisbits(x)
Returntrue
ifx
is an instance of anisbitstype
type.
Base.isbitstype
—Functionisbitstype(T)
Returntrue
if typeT
is a "plain data" type, meaning it is immutable and contains no references to other values, onlyprimitive
types and otherisbitstype
types. Typical examples are numeric types such asUInt8
,Float64
, andComplex{Float64}
. This category of types is significant since they are valid as type parameters, may not trackisdefined
/isassigned
status, and have a defined layout that is compatible with C. IfT
is not a type, then returnfalse
.
See alsoisbits
,isprimitivetype
,ismutable
.
Examples
julia> isbitstype(Complex{Float64})truejulia> isbitstype(Complex)false
Base.fieldoffset
—Functionfieldoffset(type, i)
The byte offset of fieldi
of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct:
julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)];julia> structinfo(Base.Filesystem.StatStruct)13-element Vector{Tuple{UInt64, Symbol, Type}}: (0x0000000000000000, :desc, Union{RawFD, String}) (0x0000000000000008, :device, UInt64) (0x0000000000000010, :inode, UInt64) (0x0000000000000018, :mode, UInt64) (0x0000000000000020, :nlink, Int64) (0x0000000000000028, :uid, UInt64) (0x0000000000000030, :gid, UInt64) (0x0000000000000038, :rdev, UInt64) (0x0000000000000040, :size, Int64) (0x0000000000000048, :blksize, Int64) (0x0000000000000050, :blocks, Int64) (0x0000000000000058, :mtime, Float64) (0x0000000000000060, :ctime, Float64)
Base.datatype_alignment
—FunctionBase.datatype_alignment(dt::DataType) -> Int
Memory allocation minimum alignment for instances of this type. Can be called on anyisconcretetype
, although for Memory it will give the alignment of the elements, not the whole object.
Base.datatype_haspadding
—FunctionBase.datatype_haspadding(dt::DataType) -> Bool
Return whether the fields of instances of this type are packed in memory, with no intervening padding bits (defined as bits whose value does not uniquely impact the egal test when applied to the struct fields). Can be called on anyisconcretetype
.
Base.datatype_pointerfree
—FunctionBase.datatype_pointerfree(dt::DataType) -> Bool
Return whether instances of this type can contain references to gc-managed memory. Can be called on anyisconcretetype
.
Base.typemin
—Functiontypemin(T)
The lowest value representable by the given (real) numeric DataTypeT
.
See also:floatmin
,typemax
,eps
.
Examples
julia> typemin(Int8)-128julia> typemin(UInt32)0x00000000julia> typemin(Float16)-Inf16julia> typemin(Float32)-Inf32julia> nextfloat(-Inf32) # smallest finite Float32 floating point number-3.4028235f38
Base.typemax
—Functiontypemax(T)
The highest value representable by the given (real) numericDataType
.
See also:floatmax
,typemin
,eps
.
Examples
julia> typemax(Int8)127julia> typemax(UInt32)0xffffffffjulia> typemax(Float64)Infjulia> typemax(Float32)Inf32julia> floatmax(Float32) # largest finite Float32 floating point number3.4028235f38
Base.floatmin
—Functionfloatmin(T = Float64)
Return the smallest positive normal number representable by the floating-point typeT
.
Examples
julia> floatmin(Float16)Float16(6.104e-5)julia> floatmin(Float32)1.1754944f-38julia> floatmin()2.2250738585072014e-308
Base.floatmax
—Functionfloatmax(T = Float64)
Return the largest finite number representable by the floating-point typeT
.
See also:typemax
,floatmin
,eps
.
Examples
julia> floatmax(Float16)Float16(6.55e4)julia> floatmax(Float32)3.4028235f38julia> floatmax()1.7976931348623157e308julia> typemax(Float64)Inf
Base.maxintfloat
—Functionmaxintfloat(T=Float64)
The largest consecutive integer-valued floating-point number that is exactly represented in the given floating-point typeT
(which defaults toFloat64
).
That is,maxintfloat
returns the smallest positive integer-valued floating-point numbern
such thatn+1
isnot exactly representable in the typeT
.
When anInteger
-type value is needed, useInteger(maxintfloat(T))
.
maxintfloat(T, S)
The largest consecutive integer representable in the given floating-point typeT
that also does not exceed the maximum integer representable by the integer typeS
. Equivalently, it is the minimum ofmaxintfloat(T)
andtypemax(S)
.
Base.eps
—Methodeps(::Type{T}) where T<:AbstractFloateps()
Return themachine epsilon of the floating point typeT
(T = Float64
by default). This is defined as the gap between 1 and the next largest value representable bytypeof(one(T))
, and is equivalent toeps(one(T))
. (Sinceeps(T)
is a bound on therelative error ofT
, it is a "dimensionless" quantity likeone
.)
Examples
julia> eps()2.220446049250313e-16julia> eps(Float32)1.1920929f-7julia> 1.0 + eps()1.0000000000000002julia> 1.0 + eps()/21.0
Base.eps
—Methodeps(x::AbstractFloat)
Return theunit in last place (ulp) ofx
. This is the distance between consecutive representable floating point values atx
. In most cases, if the distance on either side ofx
is different, then the larger of the two is taken, that is
eps(x) == max(x-prevfloat(x), nextfloat(x)-x)
The exceptions to this rule are the smallest and largest finite values (e.g.nextfloat(-Inf)
andprevfloat(Inf)
forFloat64
), which round to the smaller of the values.
The rationale for this behavior is thateps
bounds the floating point rounding error. Under the defaultRoundNearest
rounding mode, if$y$ is a real number and$x$ is the nearest floating point number to$y$, then
\[|y-x| \leq \operatorname{eps}(x)/2.\]
See also:nextfloat
,issubnormal
,floatmax
.
Examples
julia> eps(1.0)2.220446049250313e-16julia> eps(prevfloat(2.0))2.220446049250313e-16julia> eps(2.0)4.440892098500626e-16julia> x = prevfloat(Inf) # largest finite Float641.7976931348623157e308julia> x + eps(x)/2 # rounds upInfjulia> x + prevfloat(eps(x)/2) # rounds down1.7976931348623157e308
Base.instances
—Functioninstances(T::Type)
Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see@enum
).
Examples
julia> @enum Color red blue greenjulia> instances(Color)(red, blue, green)
Core.Any
—TypeAny::DataType
Any
is the union of all types. It has the defining propertyisa(x, Any) == true
for anyx
.Any
therefore describes the entire universe of possible values. For exampleInteger
is a subset ofAny
that includesInt
,Int8
, and other integer types.
Core.Union
—TypeUnion{Types...}
AUnion
type is an abstract type which includes all instances of any of its argument types. This means thatT <: Union{T,S}
andS <: Union{T,S}
.
Like other abstract types, it cannot be instantiated, even if all of its arguments are non abstract.
Examples
julia> IntOrString = Union{Int,AbstractString}Union{Int64, AbstractString}julia> 1 isa IntOrString # instance of Int is included in the uniontruejulia> "Hello!" isa IntOrString # String is also includedtruejulia> 1.0 isa IntOrString # Float64 is not included because it is neither Int nor AbstractStringfalse
Extended Help
Unlike most other parametric types, unions are covariant in their parameters. For example,Union{Real, String}
is a subtype ofUnion{Number, AbstractString}
.
The empty unionUnion{}
is the bottom type of Julia.
Union{}
—KeywordUnion{}
Union{}
, the emptyUnion
of types, is the type that has no values. That is, it has the defining propertyisa(x, Union{}) == false
for anyx
.Base.Bottom
is defined as its alias and the type ofUnion{}
isCore.TypeofBottom
.
Examples
julia> isa(nothing, Union{})false
Core.UnionAll
—TypeUnionAll
A union of types over all values of a type parameter.UnionAll
is used to describe parametric types where the values of some parameters are not known. See the manual section onUnionAll Types.
Examples
julia> typeof(Vector)UnionAlljulia> typeof(Vector{Int})DataType
Core.Tuple
—TypeTuple{Types...}
A tuple is a fixed-length container that can hold any values of different types, but cannot be modified (it is immutable). The values can be accessed via indexing. Tuple literals are written with commas and parentheses:
julia> (1, 1+1)(1, 2)julia> (1,)(1,)julia> x = (0.0, "hello", 6*7)(0.0, "hello", 42)julia> x[2]"hello"julia> typeof(x)Tuple{Float64, String, Int64}
A length-1 tuple must be written with a comma,(1,)
, since(1)
would just be a parenthesized value.()
represents the empty (length-0) tuple.
A tuple can be constructed from an iterator by using aTuple
type as constructor:
julia> Tuple(["a", 1])("a", 1)julia> Tuple{String, Float64}(["a", 1])("a", 1.0)
Tuple types are covariant in their parameters:Tuple{Int}
is a subtype ofTuple{Any}
. ThereforeTuple{Any}
is considered an abstract type, and tuple types are only concrete if their parameters are. Tuples do not have field names; fields are only accessed by index. Tuple types may have any number of parameters.
See the manual section onTuple Types.
See alsoVararg
,NTuple
,ntuple
,tuple
,NamedTuple
.
Core.NTuple
—TypeNTuple{N, T}
A compact way of representing the type for a tuple of lengthN
where all elements are of typeT
.
Examples
julia> isa((1, 2, 3, 4, 5, 6), NTuple{6, Int})true
See alsontuple
.
Core.NamedTuple
—TypeNamedTuple
NamedTuple
s are, as their name suggests, namedTuple
s. That is, they're a tuple-like collection of values, where each entry has a unique name, represented as aSymbol
. LikeTuple
s,NamedTuple
s are immutable; neither the names nor the values can be modified in place after construction.
A named tuple can be created as a tuple literal with keys, e.g.(a=1, b=2)
, or as a tuple literal with semicolon after the opening parenthesis, e.g.(; a=1, b=2)
(this form also accepts programmatically generated names as described below), or using aNamedTuple
type as constructor, e.g.NamedTuple{(:a, :b)}((1,2))
.
Accessing the value associated with a name in a named tuple can be done using field access syntax, e.g.x.a
, or usinggetindex
, e.g.x[:a]
orx[(:a, :b)]
. A tuple of the names can be obtained usingkeys
, and a tuple of the values can be obtained usingvalues
.
Iteration overNamedTuple
s produces thevalues without the names. (See example below.) To iterate over the name-value pairs, use thepairs
function.
The@NamedTuple
macro can be used for conveniently declaringNamedTuple
types.
Examples
julia> x = (a=1, b=2)(a = 1, b = 2)julia> x.a1julia> x[:a]1julia> x[(:a,)](a = 1,)julia> keys(x)(:a, :b)julia> values(x)(1, 2)julia> collect(x)2-element Vector{Int64}: 1 2julia> collect(pairs(x))2-element Vector{Pair{Symbol, Int64}}: :a => 1 :b => 2
In a similar fashion as to how one can define keyword arguments programmatically, a named tuple can be created by giving pairsname::Symbol => value
after a semicolon inside a tuple literal. This and thename=value
syntax can be mixed:
julia> (; :a => 1, :b => 2, c=3)(a = 1, b = 2, c = 3)
The name-value pairs can also be provided by splatting a named tuple or any iterator that yields two-value collections holding each a symbol as first value:
julia> keys = (:a, :b, :c); values = (1, 2, 3);julia> NamedTuple{keys}(values)(a = 1, b = 2, c = 3)julia> (; (keys .=> values)...)(a = 1, b = 2, c = 3)julia> nt1 = (a=1, b=2);julia> nt2 = (c=3, d=4);julia> (; nt1..., nt2..., b=20) # the final b overwrites the value from nt1(a = 1, b = 20, c = 3, d = 4)julia> (; zip(keys, values)...) # zip yields tuples such as (:a, 1)(a = 1, b = 2, c = 3)
As in keyword arguments, identifiers and dot expressions imply names:
julia> x = 00julia> t = (; x)(x = 0,)julia> (; t.x)(x = 0,)
Implicit names from identifiers and dot expressions are available as of Julia 1.5.
Use ofgetindex
methods with multipleSymbol
s is available as of Julia 1.7.
Base.@NamedTuple
—Macro@NamedTuple{key1::Type1, key2::Type2, ...}@NamedTuple begin key1::Type1; key2::Type2; ...; end
This macro gives a more convenient syntax for declaringNamedTuple
types. It returns aNamedTuple
type with the given keys and types, equivalent toNamedTuple{(:key1, :key2, ...), Tuple{Type1,Type2,...}}
. If the::Type
declaration is omitted, it is taken to beAny
. Thebegin ... end
form allows the declarations to be split across multiple lines (similar to astruct
declaration), but is otherwise equivalent. TheNamedTuple
macro is used when printingNamedTuple
types to e.g. the REPL.
For example, the tuple(a=3.1, b="hello")
has a typeNamedTuple{(:a, :b), Tuple{Float64, String}}
, which can also be declared via@NamedTuple
as:
julia> @NamedTuple{a::Float64, b::String}@NamedTuple{a::Float64, b::String}julia> @NamedTuple begin a::Float64 b::String end@NamedTuple{a::Float64, b::String}
This macro is available as of Julia 1.5.
Base.@Kwargs
—Macro@Kwargs{key1::Type1, key2::Type2, ...}
This macro gives a convenient way to construct the type representation of keyword arguments from the same syntax as@NamedTuple
. For example, when we have a function call likefunc([positional arguments]; kw1=1.0, kw2="2")
, we can use this macro to construct the internal type representation of the keyword arguments as@Kwargs{kw1::Float64, kw2::String}
. The macro syntax is specifically designed to simplify the signature type of a keyword method when it is printed in the stack trace view.
julia> @Kwargs{init::Int} # the internal representation of keyword argumentsBase.Pairs{Symbol, Int64, Tuple{Symbol}, @NamedTuple{init::Int64}}julia> sum("julia"; init=1)ERROR: MethodError: no method matching +(::Char, ::Char)The function `+` exists, but no method is defined for this combination of argument types.Closest candidates are: +(::Any, ::Any, ::Any, ::Any...) @ Base operators.jl:585 +(::Integer, ::AbstractChar) @ Base char.jl:247 +(::T, ::Integer) where T<:AbstractChar @ Base char.jl:237Stacktrace: [1] add_sum(x::Char, y::Char) @ Base ./reduce.jl:24 [2] BottomRF @ Base ./reduce.jl:86 [inlined] [3] _foldl_impl(op::Base.BottomRF{typeof(Base.add_sum)}, init::Int64, itr::String) @ Base ./reduce.jl:62 [4] foldl_impl(op::Base.BottomRF{typeof(Base.add_sum)}, nt::Int64, itr::String) @ Base ./reduce.jl:48 [inlined] [5] mapfoldl_impl(f::typeof(identity), op::typeof(Base.add_sum), nt::Int64, itr::String) @ Base ./reduce.jl:44 [inlined] [6] mapfoldl(f::typeof(identity), op::typeof(Base.add_sum), itr::String; init::Int64) @ Base ./reduce.jl:175 [inlined] [7] mapreduce(f::typeof(identity), op::typeof(Base.add_sum), itr::String; kw::@Kwargs{init::Int64}) @ Base ./reduce.jl:307 [inlined] [8] sum(f::typeof(identity), a::String; kw::@Kwargs{init::Int64}) @ Base ./reduce.jl:535 [inlined] [9] sum(a::String; kw::@Kwargs{init::Int64}) @ Base ./reduce.jl:564 [inlined] [10] top-level scope @ REPL[12]:1
This macro is available as of Julia 1.10.
Base.Val
—TypeVal(c)
ReturnVal{c}()
, which contains no run-time data. Types like this can be used to pass the information between functions through the valuec
, which must be anisbits
value or aSymbol
. The intent of this construct is to be able to dispatch on constants directly (at compile time) without having to test the value of the constant at run time.
Examples
julia> f(::Val{true}) = "Good"f (generic function with 1 method)julia> f(::Val{false}) = "Bad"f (generic function with 2 methods)julia> f(Val(true))"Good"
Core.Vararg
—ConstantVararg{T,N}
The last parameter of a tuple typeTuple
can be the special valueVararg
, which denotes any number of trailing elements.Vararg{T,N}
corresponds to exactlyN
elements of typeT
. FinallyVararg{T}
corresponds to zero or more elements of typeT
.Vararg
tuple types are used to represent the arguments accepted by varargs methods (see the section onVarargs Functions in the manual.)
See alsoNTuple
.
Examples
julia> mytupletype = Tuple{AbstractString, Vararg{Int}}Tuple{AbstractString, Vararg{Int64}}julia> isa(("1",), mytupletype)truejulia> isa(("1",1), mytupletype)truejulia> isa(("1",1,2), mytupletype)truejulia> isa(("1",1,2,3.0), mytupletype)false
Core.Nothing
—TypeBase.isnothing
—Functionisnothing(x)
Returntrue
ifx === nothing
, and returnfalse
if not.
This function requires at least Julia 1.1.
See alsosomething
,Base.notnothing
,ismissing
.
Base.notnothing
—Functionnotnothing(x)
Throw an error ifx === nothing
, and returnx
if not.
Base.Some
—TypeSome{T}
A wrapper type used inUnion{Some{T}, Nothing}
to distinguish between the absence of a value (nothing
) and the presence of anothing
value (i.e.Some(nothing)
).
Usesomething
to access the value wrapped by aSome
object.
Base.something
—Functionsomething(x...)
Return the first value in the arguments which is not equal tonothing
, if any. Otherwise throw an error. Arguments of typeSome
are unwrapped.
See alsocoalesce
,skipmissing
,@something
.
Examples
julia> something(nothing, 1)1julia> something(Some(1), nothing)1julia> something(Some(nothing), 2) === nothingtruejulia> something(missing, nothing)missingjulia> something(nothing, nothing)ERROR: ArgumentError: No value arguments present
Base.@something
—Macro@something(x...)
Short-circuiting version ofsomething
.
Examples
julia> f(x) = (println("f($x)"); nothing);julia> a = 1;julia> a = @something a f(2) f(3) error("Unable to find default for `a`")1julia> b = nothing;julia> b = @something b f(2) f(3) error("Unable to find default for `b`")f(2)f(3)ERROR: Unable to find default for `b`[...]julia> b = @something b f(2) f(3) Some(nothing)f(2)f(3)julia> b === nothingtrue
This macro is available as of Julia 1.7.
Base.Enums.Enum
—TypeEnum{T<:Integer}
The abstract supertype of all enumerated types defined with@enum
.
Base.Enums.@enum
—Macro@enum EnumName[::BaseType] value1[=x] value2[=y]
Create anEnum{BaseType}
subtype with nameEnumName
and enum member values ofvalue1
andvalue2
with optional assigned values ofx
andy
, respectively.EnumName
can be used just like other types and enum member values as regular values, such as
Examples
julia> @enum Fruit apple=1 orange=2 kiwi=3julia> f(x::Fruit) = "I'm a Fruit with value: $(Int(x))"f (generic function with 1 method)julia> f(apple)"I'm a Fruit with value: 1"julia> Fruit(1)apple::Fruit = 1
Values can also be specified inside abegin
block, e.g.
@enum EnumName begin value1 value2end
BaseType
, which defaults toInt32
, must be a primitive subtype ofInteger
. Member values can be converted between the enum type andBaseType
.read
andwrite
perform these conversions automatically. In case the enum is created with a non-defaultBaseType
,Integer(value1)
will return the integervalue1
with the typeBaseType
.
To list all the instances of an enum useinstances
, e.g.
julia> instances(Fruit)(apple, orange, kiwi)
It is possible to construct a symbol from an enum instance:
julia> Symbol(apple):apple
Core.Expr
—TypeExpr(head::Symbol, args...)
A type representing compound expressions in parsed julia code (ASTs). Each expression consists of ahead
Symbol
identifying which kind of expression it is (e.g. a call, for loop, conditional statement, etc.), and subexpressions (e.g. the arguments of a call). The subexpressions are stored in aVector{Any}
field calledargs
.
See the manual chapter onMetaprogramming and the developer documentationJulia ASTs.
Examples
julia> Expr(:call, :+, 1, 2):(1 + 2)julia> dump(:(a ? b : c))Expr head: Symbol if args: Array{Any}((3,)) 1: Symbol a 2: Symbol b 3: Symbol c
Core.Symbol
—TypeSymbol
The type of object used to represent identifiers in parsed julia code (ASTs). Also often used as a name or label to identify an entity (e.g. as a dictionary key).Symbol
s can be entered using the:
quote operator:
julia> :name:namejulia> typeof(:name)Symboljulia> x = 4242julia> eval(:x)42
Symbol
s can also be constructed from strings or other values by calling the constructorSymbol(x...)
.
Symbol
s are immutable and their implementation re-uses the same object for allSymbol
s with the same name.
Unlike strings,Symbol
s are "atomic" or "scalar" entities that do not support iteration over characters.
Core.Symbol
—MethodSymbol(x...) -> Symbol
Create aSymbol
by concatenating the string representations of the arguments together.
Examples
julia> Symbol("my", "name"):mynamejulia> Symbol("day", 4):day4
Core.Module
—TypeModule
AModule
is a separate global variable workspace. Seemodule
and themanual section about modules for details.
Module(name::Symbol=:anonymous, std_imports=true, default_names=true)
Return a module with the specified name. Abaremodule
corresponds toModule(:ModuleName, false)
An empty module containing no names at all can be created withModule(:ModuleName, false, false)
. This module will not importBase
orCore
and does not contain a reference to itself.
Core.Function
—TypeFunction
Abstract type of all functions.
Examples
julia> isa(+, Function)truejulia> typeof(sin)typeof(sin) (singleton type of function sin, subtype of Function)julia> ans <: Functiontrue
Base.hasmethod
—Functionhasmethod(f, t::Type{<:Tuple}[, kwnames]; world=get_world_counter()) -> Bool
Determine whether the given generic function has a method matching the givenTuple
of argument types with the upper bound of world age given byworld
.
If a tuple of keyword argument nameskwnames
is provided, this also checks whether the method off
matchingt
has the given keyword argument names. If the matching method accepts a variable number of keyword arguments, e.g. withkwargs...
, any names given inkwnames
are considered valid. Otherwise the provided names must be a subset of the method's keyword arguments.
See alsoapplicable
.
Providing keyword argument names requires Julia 1.2 or later.
Examples
julia> hasmethod(length, Tuple{Array})truejulia> f(; oranges=0) = oranges;julia> hasmethod(f, Tuple{}, (:oranges,))truejulia> hasmethod(f, Tuple{}, (:apples, :bananas))falsejulia> g(; xs...) = 4;julia> hasmethod(g, Tuple{}, (:a, :b, :c, :d)) # g accepts arbitrary kwargstrue
Core.applicable
—Functionapplicable(f, args...) -> Bool
Determine whether the given generic function has a method applicable to the given arguments.
See alsohasmethod
.
Examples
julia> function f(x, y) x + y end;julia> applicable(f, 1)falsejulia> applicable(f, 1, 2)true
Base.isambiguous
—FunctionBase.isambiguous(m1, m2; ambiguous_bottom=false) -> Bool
Determine whether two methodsm1
andm2
may be ambiguous for some call signature. This test is performed in the context of other methods of the same function; in isolation,m1
andm2
might be ambiguous, but if a third method resolving the ambiguity has been defined, this returnsfalse
. Alternatively, in isolationm1
andm2
might be ordered, but if a third method cannot be sorted with them, they may cause an ambiguity together.
For parametric types, theambiguous_bottom
keyword argument controls whetherUnion{}
counts as an ambiguous intersection of type parameters – whentrue
, it is considered ambiguous, whenfalse
it is not.
Examples
julia> foo(x::Complex{<:Integer}) = 1foo (generic function with 1 method)julia> foo(x::Complex{<:Rational}) = 2foo (generic function with 2 methods)julia> m1, m2 = collect(methods(foo));julia> typeintersect(m1.sig, m2.sig)Tuple{typeof(foo), Complex{Union{}}}julia> Base.isambiguous(m1, m2, ambiguous_bottom=true)truejulia> Base.isambiguous(m1, m2, ambiguous_bottom=false)false
Core.invoke
—Functioninvoke(f, argtypes::Type, args...; kwargs...)
Invoke a method for the given generic functionf
matching the specified typesargtypes
on the specified argumentsargs
and passing the keyword argumentskwargs
. The argumentsargs
must conform with the specified types inargtypes
, i.e. conversion is not automatically performed. This method allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).
Be careful when usinginvoke
for functions that you don't write. What definition is used for givenargtypes
is an implementation detail unless the function is explicitly states that calling with certainargtypes
is a part of public API. For example, the change betweenf1
andf2
in the example below is usually considered compatible because the change is invisible by the caller with a normal (non-invoke
) call. However, the change is visible if you useinvoke
.
Examples
julia> f(x::Real) = x^2;julia> f(x::Integer) = 1 + invoke(f, Tuple{Real}, x);julia> f(2)5julia> f1(::Integer) = Integer f1(::Real) = Real;julia> f2(x::Real) = _f2(x) _f2(::Integer) = Integer _f2(_) = Real;julia> f1(1)Integerjulia> f2(1)Integerjulia> invoke(f1, Tuple{Real}, 1)Realjulia> invoke(f2, Tuple{Real}, 1)Integer
Base.@invoke
—Macro@invoke f(arg::T, ...; kwargs...)
Provides a convenient way to callinvoke
by expanding@invoke f(arg1::T1, arg2::T2; kwargs...)
toinvoke(f, Tuple{T1,T2}, arg1, arg2; kwargs...)
. When an argument's type annotation is omitted, it's replaced withCore.Typeof
that argument. To invoke a method where an argument is untyped or explicitly typed asAny
, annotate the argument with::Any
.
It also supports the following syntax:
@invoke (x::X).f
expands toinvoke(getproperty, Tuple{X,Symbol}, x, :f)
@invoke (x::X).f = v::V
expands toinvoke(setproperty!, Tuple{X,Symbol,V}, x, :f, v)
@invoke (xs::Xs)[i::I]
expands toinvoke(getindex, Tuple{Xs,I}, xs, i)
@invoke (xs::Xs)[i::I] = v::V
expands toinvoke(setindex!, Tuple{Xs,V,I}, xs, v, i)
Examples
julia> @macroexpand @invoke f(x::T, y):(Core.invoke(f, Tuple{T, Core.Typeof(y)}, x, y))julia> @invoke 420::Integer % Unsigned0x00000000000001a4julia> @macroexpand @invoke (x::X).f:(Core.invoke(Base.getproperty, Tuple{X, Core.Typeof(:f)}, x, :f))julia> @macroexpand @invoke (x::X).f = v::V:(Core.invoke(Base.setproperty!, Tuple{X, Core.Typeof(:f), V}, x, :f, v))julia> @macroexpand @invoke (xs::Xs)[i::I]:(Core.invoke(Base.getindex, Tuple{Xs, I}, xs, i))julia> @macroexpand @invoke (xs::Xs)[i::I] = v::V:(Core.invoke(Base.setindex!, Tuple{Xs, V, I}, xs, v, i))
This macro requires Julia 1.7 or later.
This macro is exported as of Julia 1.9.
The additional syntax is supported as of Julia 1.10.
Base.invokelatest
—Functioninvokelatest(f, args...; kwargs...)
Callsf(args...; kwargs...)
, but guarantees that the most recent method off
will be executed. This is useful in specialized circumstances, e.g. long-running event loops or callback functions that may call obsolete versions of a functionf
. (The drawback is thatinvokelatest
is somewhat slower than callingf
directly, and the type of the result cannot be inferred by the compiler.)
Prior to Julia 1.9, this function was not exported, and was called asBase.invokelatest
.
Base.@invokelatest
—Macro@invokelatest f(args...; kwargs...)
Provides a convenient way to callinvokelatest
.@invokelatest f(args...; kwargs...)
will simply be expanded intoBase.invokelatest(f, args...; kwargs...)
.
It also supports the following syntax:
@invokelatest x.f
expands toBase.invokelatest(getproperty, x, :f)
@invokelatest x.f = v
expands toBase.invokelatest(setproperty!, x, :f, v)
@invokelatest xs[i]
expands toBase.invokelatest(getindex, xs, i)
@invokelatest xs[i] = v
expands toBase.invokelatest(setindex!, xs, v, i)
julia> @macroexpand @invokelatest f(x; kw=kwv):(Base.invokelatest(f, x; kw = kwv))julia> @macroexpand @invokelatest x.f:(Base.invokelatest(Base.getproperty, x, :f))julia> @macroexpand @invokelatest x.f = v:(Base.invokelatest(Base.setproperty!, x, :f, v))julia> @macroexpand @invokelatest xs[i]:(Base.invokelatest(Base.getindex, xs, i))julia> @macroexpand @invokelatest xs[i] = v:(Base.invokelatest(Base.setindex!, xs, v, i))
This macro requires Julia 1.7 or later.
Prior to Julia 1.9, this macro was not exported, and was called asBase.@invokelatest
.
The additionalx.f
andxs[i]
syntax requires Julia 1.10.
new
—Keywordnew, or new{A,B,...}
Special function available to inner constructors which creates a new object of the type. The form new{A,B,...} explicitly specifies values of parameters for parametric types. See the manual section onInner Constructor Methods for more information.
Base.:|>
—Function|>(x, f)
Infix operator which applies functionf
to the argumentx
. This allowsf(g(x))
to be writtenx |> g |> f
. When used with anonymous functions, parentheses are typically required around the definition to get the intended chain.
Examples
julia> 4 |> inv0.25julia> [2, 3, 5] |> sum |> inv0.1julia> [0 1; 2 3] .|> (x -> x^2) |> sum14
Base.:∘
—Functionf ∘ g
Compose functions: i.e.(f ∘ g)(args...; kwargs...)
meansf(g(args...; kwargs...))
. The∘
symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing\circ<tab>
.
Function composition also works in prefix form:∘(f, g)
is the same asf ∘ g
. The prefix form supports composition of multiple functions:∘(f, g, h) = f ∘ g ∘ h
and splatting∘(fs...)
for composing an iterable collection of functions. The last argument to∘
execute first.
Multiple function composition requires at least Julia 1.4.
Composition of one function ∘(f) requires at least Julia 1.5.
Using keyword arguments requires at least Julia 1.7.
Examples
julia> map(uppercase∘first, ["apple", "banana", "carrot"])3-element Vector{Char}: 'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase) 'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase) 'C': ASCII/Unicode U+0043 (category Lu: Letter, uppercase)julia> (==(6)∘length).(["apple", "banana", "carrot"])3-element BitVector: 0 1 1julia> fs = [ x -> 2x x -> x-1 x -> x/2 x -> x+1 ];julia> ∘(fs...)(3)2.0
See alsoComposedFunction
,!f::Function
.
Base.ComposedFunction
—TypeComposedFunction{Outer,Inner} <: Function
Represents the composition of two callable objectsouter::Outer
andinner::Inner
. That is
ComposedFunction(outer, inner)(args...; kw...) === outer(inner(args...; kw...))
The preferred way to construct an instance ofComposedFunction
is to use the composition operator∘
:
julia> sin ∘ cos === ComposedFunction(sin, cos)truejulia> typeof(sin∘cos)ComposedFunction{typeof(sin), typeof(cos)}
The composed pieces are stored in the fields ofComposedFunction
and can be retrieved as follows:
julia> composition = sin ∘ cossin ∘ cosjulia> composition.outer === sintruejulia> composition.inner === costrue
ComposedFunction requires at least Julia 1.6. In earlier versions∘
returns an anonymous function instead.
See also∘
.
Base.splat
—Functionsplat(f)
Equivalent to
my_splat(f) = args->f(args...)
i.e. given a function returns a new function that takes one argument and splats it into the original function. This is useful as an adaptor to pass a multi-argument function in a context that expects a single argument, but passes a tuple as that single argument.
Examples
julia> map(splat(+), zip(1:3,4:6))3-element Vector{Int64}: 5 7 9julia> my_add = splat(+)splat(+)julia> my_add((1,2,3))6
Base.Fix1
—TypeFix1(f, x)
A type representing a partially-applied version of the two-argument functionf
, with the first argument fixed to the value "x". In other words,Fix1(f, x)
behaves similarly toy->f(x, y)
.
See alsoFix2
.
Base.Fix2
—TypeFix2(f, x)
A type representing a partially-applied version of the two-argument functionf
, with the second argument fixed to the value "x". In other words,Fix2(f, x)
behaves similarly toy->f(y, x)
.
Core.eval
—FunctionCore.eval(m::Module, expr)
Evaluate an expression in the given module and return the result.
eval
—Functioneval(expr)
Evaluate an expression in the global scope of the containing module. EveryModule
(except those defined withbaremodule
) has its own 1-argument definition ofeval
, which evaluates expressions in that module.
Base.@eval
—Macro@eval [mod,] ex
Evaluate an expression with values interpolated into it usingeval
. If two arguments are provided, the first is the module to evaluate in.
Base.evalfile
—Functionevalfile(path::AbstractString, args::Vector{String}=String[])
Load the file into an anonymous module usinginclude
, evaluate all expressions, and return the value of the last expression. The optionalargs
argument can be used to set the input arguments of the script (i.e. the globalARGS
variable). Note that definitions (e.g. methods, globals) are evaluated in the anonymous module and do not affect the current module.
Examples
julia> write("testfile.jl", """ @show ARGS 1 + 1 """);julia> x = evalfile("testfile.jl", ["ARG1", "ARG2"]);ARGS = ["ARG1", "ARG2"]julia> x2julia> rm("testfile.jl")
Base.esc
—Functionesc(e)
Only valid in the context of anExpr
returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See theMacros section of the Metaprogramming chapter of the manual for more details and examples.
Base.@inbounds
—Macro@inbounds(blk)
Eliminates array bounds checking within expressions.
In the example below the in-range check for referencing elementi
of arrayA
is skipped to improve performance.
function sum(A::AbstractArray) r = zero(eltype(A)) for i in eachindex(A) @inbounds r += A[i] end return rend
Using@inbounds
may return incorrect results/crashes/corruption for out-of-bounds indices. The user is responsible for checking it manually. Only use@inbounds
when it is certain from the information locally available that all accesses are in bounds. In particular, using1:length(A)
instead ofeachindex(A)
in a function like the one above isnot safely inbounds because the first index ofA
may not be1
for all user defined types that subtypeAbstractArray
.
Base.@boundscheck
—Macro@boundscheck(blk)
Annotates the expressionblk
as a bounds checking block, allowing it to be elided by@inbounds
.
The function in which@boundscheck
is written must be inlined into its caller in order for@inbounds
to have effect.
Examples
julia> @inline function g(A, i) @boundscheck checkbounds(A, i) return "accessing ($A)[$i]" end;julia> f1() = return g(1:2, -1);julia> f2() = @inbounds return g(1:2, -1);julia> f1()ERROR: BoundsError: attempt to access 2-element UnitRange{Int64} at index [-1]Stacktrace: [1] throw_boundserror(::UnitRange{Int64}, ::Tuple{Int64}) at ./abstractarray.jl:455 [2] checkbounds at ./abstractarray.jl:420 [inlined] [3] g at ./none:2 [inlined] [4] f1() at ./none:1 [5] top-level scopejulia> f2()"accessing (1:2)[-1]"
The@boundscheck
annotation allows you, as a library writer, to opt-in to allowingother code to remove your bounds checks with@inbounds
. As noted there, the caller must verify—using information they can access—that their accesses are valid before using@inbounds
. For indexing into yourAbstractArray
subclasses, for example, this involves checking the indices against itsaxes
. Therefore,@boundscheck
annotations should only be added to agetindex
orsetindex!
implementation after you are certain its behavior is correct.
Base.@propagate_inbounds
—Macro@propagate_inbounds
Tells the compiler to inline a function while retaining the caller's inbounds context.
Base.@inline
—Macro@inline
Give a hint to the compiler that this function is worth inlining.
Small functions typically do not need the@inline
annotation, as the compiler does it automatically. By using@inline
on bigger functions, an extra nudge can be given to the compiler to inline it.
@inline
can be applied immediately before a function definition or within a function body.
# annotate long-form definition@inline function longdef(x) ...end# annotate short-form definition@inline shortdef(x) = ...# annotate anonymous function that a `do` block createsf() do @inline ...end
The usage within a function body requires at least Julia 1.8.
@inline block
Give a hint to the compiler that calls withinblock
are worth inlining.
# The compiler will try to inline `f`@inline f(...)# The compiler will try to inline `f`, `g` and `+`@inline f(...) + g(...)
A callsite annotation always has the precedence over the annotation applied to the definition of the called function:
@noinline function explicit_noinline(args...) # bodyendlet @inline explicit_noinline(args...) # will be inlinedend
When there are nested callsite annotations, the innermost annotation has the precedence:
@noinline let a0, b0 = ... a = @inline f(a0) # the compiler will try to inline this call b = f(b0) # the compiler will NOT try to inline this call return a, bend
Although a callsite annotation will try to force inlining in regardless of the cost model, there are still chances it can't succeed in it. Especially, recursive calls can not be inlined even if they are annotated as@inline
d.
The callsite annotation requires at least Julia 1.8.
Base.@noinline
—Macro@noinline
Give a hint to the compiler that it should not inline a function.
Small functions are typically inlined automatically. By using@noinline
on small functions, auto-inlining can be prevented.
@noinline
can be applied immediately before a function definition or within a function body.
# annotate long-form definition@noinline function longdef(x) ...end# annotate short-form definition@noinline shortdef(x) = ...# annotate anonymous function that a `do` block createsf() do @noinline ...end
The usage within a function body requires at least Julia 1.8.
@noinline block
Give a hint to the compiler that it should not inline the calls withinblock
.
# The compiler will try to not inline `f`@noinline f(...)# The compiler will try to not inline `f`, `g` and `+`@noinline f(...) + g(...)
A callsite annotation always has the precedence over the annotation applied to the definition of the called function:
@inline function explicit_inline(args...) # bodyendlet @noinline explicit_inline(args...) # will not be inlinedend
When there are nested callsite annotations, the innermost annotation has the precedence:
@inline let a0, b0 = ... a = @noinline f(a0) # the compiler will NOT try to inline this call b = f(b0) # the compiler will try to inline this call return a, bend
The callsite annotation requires at least Julia 1.8.
If the function is trivial (for example returning a constant) it might get inlined anyway.
Base.@nospecialize
—Macro@nospecialize
Applied to a function argument name, hints to the compiler that the method implementation should not be specialized for different types of that argument, but instead use the declared type for that argument. It can be applied to an argument within a formal argument list, or in the function body. When applied to an argument, the macro must wrap the entire argument expression, e.g.,@nospecialize(x::Real)
or@nospecialize(i::Integer...)
rather than wrapping just the argument name. When used in a function body, the macro must occur in statement position and before any code.
When used without arguments, it applies to all arguments of the parent scope. In local scope, this means all arguments of the containing function. In global (top-level) scope, this means all methods subsequently defined in the current module.
Specialization can reset back to the default by using@specialize
.
function example_function(@nospecialize x) ...endfunction example_function(x, @nospecialize(y = 1)) ...endfunction example_function(x, y, z) @nospecialize x y ...end@nospecializef(y) = [x for x in y]@specialize
@nospecialize
affects code generation but not inference: it limits the diversity of the resulting native code, but it does not impose any limitations (beyond the standard ones) on type-inference. UseBase.@nospecializeinfer
together with@nospecialize
to additionally suppress inference.
Examples
julia> f(A::AbstractArray) = g(A)f (generic function with 1 method)julia> @noinline g(@nospecialize(A::AbstractArray)) = A[1]g (generic function with 1 method)julia> @code_typed f([1.0])CodeInfo(1 ─ %1 = invoke Main.g(_2::AbstractArray)::Float64└── return %1) => Float64
Here, the@nospecialize
annotation results in the equivalent of
f(A::AbstractArray) = invoke(g, Tuple{AbstractArray}, A)
ensuring that only one version of native code will be generated forg
, one that is generic for anyAbstractArray
. However, the specific return type is still inferred for bothg
andf
, and this is still used in optimizing the callers off
andg
.
Base.@specialize
—Macro@specialize
Reset the specialization hint for an argument back to the default. For details, see@nospecialize
.
Base.@nospecializeinfer
—MacroBase.@nospecializeinfer function f(args...) @nospecialize ... ...endBase.@nospecializeinfer f(@nospecialize args...) = ...
Tells the compiler to inferf
using the declared types of@nospecialize
d arguments. This can be used to limit the number of compiler-generated specializations during inference.
Examples
julia> f(A::AbstractArray) = g(A)f (generic function with 1 method)julia> @noinline Base.@nospecializeinfer g(@nospecialize(A::AbstractArray)) = A[1]g (generic function with 1 method)julia> @code_typed f([1.0])CodeInfo(1 ─ %1 = invoke Main.g(_2::AbstractArray)::Any└── return %1) => Any
In this example,f
will be inferred for each specific type ofA
, butg
will only be inferred once with the declared argument typeA::AbstractArray
, meaning that the compiler will not likely see the excessive inference time on it while it can not infer the concrete return type of it. Without the@nospecializeinfer
,f([1.0])
would infer the return type ofg
asFloat64
, indicating that inference ran forg(::Vector{Float64})
despite the prohibition on specialized code generation.
UsingBase.@nospecializeinfer
requires Julia version 1.10.
Base.@constprop
—MacroBase.@constprop setting [ex]
Control the mode of interprocedural constant propagation for the annotated function.
Twosetting
s are supported:
Base.@constprop :aggressive [ex]
: apply constant propagation aggressively. For a method where the return type depends on the value of the arguments, this can yield improved inference results at the cost of additional compile time.Base.@constprop :none [ex]
: disable constant propagation. This can reduce compile times for functions that Julia might otherwise deem worthy of constant-propagation. Common cases are for functions withBool
- orSymbol
-valued arguments or keyword arguments.Base.@constprop
can be applied immediately before a function definition or within a function body.
# annotate long-form definitionBase.@constprop :aggressive function longdef(x) ...end# annotate short-form definitionBase.@constprop :aggressive shortdef(x) = ...# annotate anonymous function that a `do` block createsf() do Base.@constprop :aggressive ...end
The usage within a function body requires at least Julia 1.10.
Base.gensym
—Functiongensym([tag])
Generates a symbol which will not conflict with other variable names (in the same module).
Base.@gensym
—Macro@gensym
Generates a gensym symbol for a variable. For example,@gensym x y
is transformed intox = gensym("x"); y = gensym("y")
.
var"name"
—Keywordvar
The syntaxvar"#example#"
refers to a variable namedSymbol("#example#")
, even though#example#
is not a valid Julia identifier name.
This can be useful for interoperability with programming languages which have different rules for the construction of valid identifiers. For example, to refer to theR
variabledraw.segments
, you can usevar"draw.segments"
in your Julia code.
It is also used toshow
julia source code which has gone through macro hygiene or otherwise contains variable names which can't be parsed normally.
Note that this syntax requires parser support so it is expanded directly by the parser rather than being implemented as a normal string macro@var_str
.
This syntax requires at least Julia 1.3.
Base.@goto
—Macro@goto name
@goto name
unconditionally jumps to the statement at the location@label name
.
@label
and@goto
cannot create jumps to different top-level statements. Attempts cause an error. To still use@goto
, enclose the@label
and@goto
in a block.
Base.@label
—Macro@label name
Labels a statement with the symbolic labelname
. The label marks the end-point of an unconditional jump with@goto name
.
Base.SimdLoop.@simd
—Macro@simd
Annotate afor
loop to allow the compiler to take extra liberties to allow loop re-ordering
This feature is experimental and could change or disappear in future versions of Julia. Incorrect use of the@simd
macro may cause unexpected results.
The object iterated over in a@simd for
loop should be a one-dimensional range. By using@simd
, you are asserting several properties of the loop:
@simd
.In many cases, Julia is able to automatically vectorize inner for loops without the use of@simd
. Using@simd
gives the compiler a little extra leeway to make it possible in more situations. In either case, your inner loop should have the following properties to allow vectorization:
@inbounds
is currently needed for all array accesses. The compiler can sometimes turn short&&
,||
, and?:
expressions into straight-line code if it is safe to evaluate all operands unconditionally. Consider using theifelse
function instead of?:
in the loop if it is safe to do so.The@simd
does not assert by default that the loop is completely free of loop-carried memory dependencies, which is an assumption that can easily be violated in generic code. If you are writing non-generic code, you can use@simd ivdep for ... end
to also assert that:
Base.@polly
—Macro@polly
Tells the compiler to apply the polyhedral optimizer Polly to a function.
Base.@generated
—Macro@generated f
@generated
is used to annotate a function which will be generated. In the body of the generated function, only types of arguments can be read (not the values). The function returns a quoted expression evaluated when the function is called. The@generated
macro should not be used on functions mutating the global scope or depending on mutable elements.
SeeMetaprogramming for further details.
Examples
julia> @generated function bar(x) if x <: Integer return :(x ^ 2) else return :(x) end endbar (generic function with 1 method)julia> bar(4)16julia> bar("baz")"baz"
Base.@assume_effects
—MacroBase.@assume_effects setting... [ex]
Override the compiler's effect modeling. This macro can be used in several contexts:
Examples
julia> Base.@assume_effects :terminates_locally function fact(x) # usage 1: # this :terminates_locally allows `fact` to be constant-folded res = 1 0 ≤ x < 20 || error("bad fact") while x > 1 res *= x x -= 1 end return res endfact (generic function with 1 method)julia> code_typed() do fact(12) end |> onlyCodeInfo(1 ─ return 479001600) => Int64julia> code_typed() do map((2,3,4)) do x # usage 2: # this :terminates_locally allows this anonymous function to be constant-folded Base.@assume_effects :terminates_locally res = 1 0 ≤ x < 20 || error("bad fact") while x > 1 res *= x x -= 1 end return res end end |> onlyCodeInfo(1 ─ return (2, 6, 24)) => Tuple{Int64, Int64, Int64}julia> code_typed() do map((2,3,4)) do x res = 1 0 ≤ x < 20 || error("bad fact") # usage 3: # with this :terminates_locally annotation the compiler skips tainting # `:terminates` effect within this `while` block, allowing the parent # anonymous function to be constant-folded Base.@assume_effects :terminates_locally while x > 1 res *= x x -= 1 end return res end end |> onlyCodeInfo(1 ─ return (2, 6, 24)) => Tuple{Int64, Int64, Int64}
UsingBase.@assume_effects
requires Julia version 1.8.
The usage within a function body requires at least Julia 1.10.
The code block annotation requires at least Julia 1.11.
Improper use of this macro causes undefined behavior (including crashes, incorrect answers, or other hard to track bugs). Use with care and only as a last resort if absolutely required. Even in such a case, you SHOULD take all possible steps to minimize the strength of the effect assertion (e.g., do not use:total
if:nothrow
would have been sufficient).
In general, eachsetting
value makes an assertion about the behavior of the function, without requiring the compiler to prove that this behavior is indeed true. These assertions are made for all world ages. It is thus advisable to limit the use of generic functions that may later be extended to invalidate the assumption (which would cause undefined behavior).
The followingsetting
s are supported.
:consistent
:effect_free
:nothrow
:terminates_globally
:terminates_locally
:notaskstate
:inaccessiblememonly
:noub
:noub_if_noinbounds
:nortcall
:foldable
:removable
:total
Extended help
:consistent
The:consistent
setting asserts that for egal (===
) inputs:
This in particular implies that the method must not return a freshly allocated mutable object. Multiple allocations of mutable objects (even with identical contents) are not egal.
The:consistent
-cy assertion is made world-age wise. More formally, write$fᵢ$ for the evaluation of$f$ in world-age$i$, then this setting requires:
\[∀ i, x, y: x ≡ y → fᵢ(x) ≡ fᵢ(y)\]
However, for two world ages$i$,$j$ s.t.$i ≠ j$, we may have$fᵢ(x) ≢ fⱼ(y)$.
A further implication is that:consistent
functions may not make their return value dependent on the state of the heap or any other global state that is not constant for a given world age.
The:consistent
-cy includes all legal rewrites performed by the optimizer. For example, floating-point fastmath operations are not considered:consistent
, because the optimizer may rewrite them causing the output to not be:consistent
, even for the same world age (e.g. because one ran in the interpreter, while the other was optimized).
If:consistent
functions terminate by throwing an exception, that exception itself is not required to meet the egality requirement specified above.
:effect_free
The:effect_free
setting asserts that the method is free of externally semantically visible side effects. The following is an incomplete list of externally semantically visible side effects:
However, the following are explicitly not semantically visible, even if they may be observable:
The rule of thumb here is that an externally visible side effect is anything that would affect the execution of the remainder of the program if the function were not executed.
The:effect_free
assertion is made both for the method itself and any code that is executed by the method. Keep in mind that the assertion must be valid for all world ages and limit use of this assertion accordingly.
:nothrow
The:nothrow
settings asserts that this method does not throw an exception (i.e. will either always return a value or never return).
It is permissible for:nothrow
annotated methods to make use of exception handling internally as long as the exception is not rethrown out of the method itself.
If the execution of a method may raiseMethodError
s and similar exceptions, then the method is not considered as:nothrow
. However, note that environment-dependent errors likeStackOverflowError
orInterruptException
are not modeled by this effect and thus a method that may result inStackOverflowError
does not necessarily need to be!:nothrow
(although it should usually be!:terminates
too).
:terminates_globally
The:terminates_globally
settings asserts that this method will eventually terminate (either normally or abnormally), i.e. does not loop indefinitely.
This:terminates_globally
assertion covers any other methods called by the annotated method.
The compiler will consider this a strong indication that the method will terminate relativelyquickly and may (if otherwise legal) call this method at compile time. I.e. it is a bad idea to annotate this setting on a method thattechnically, but notpractically, terminates.
:terminates_locally
The:terminates_locally
setting is like:terminates_globally
, except that it only applies to syntactic control flowwithin the annotated method. It is thus a much weaker (and thus safer) assertion that allows for the possibility of non-termination if the method calls some other method that does not terminate.
:terminates_globally
implies:terminates_locally
.
:notaskstate
The:notaskstate
setting asserts that the method does not use or modify the local task state (task local storage, RNG state, etc.) and may thus be safely moved between tasks without observable results.
The implementation of exception handling makes use of state stored in the task object. However, this state is currently not considered to be within the scope of:notaskstate
and is tracked separately using the:nothrow
effect.
The:notaskstate
assertion concerns the state of thecurrently running task. If a reference to aTask
object is obtained by some other means that does not consider which task iscurrently running, the:notaskstate
effect need not be tainted. This is true, even if said task object happens to be===
to the currently running task.
Access to task state usually also results in the tainting of other effects, such as:effect_free
(if task state is modified) or:consistent
(if task state is used in the computation of the result). In particular, code that is not:notaskstate
, but is:effect_free
and:consistent
may still be dead-code-eliminated and thus promoted to:total
.
:inaccessiblememonly
The:inaccessiblememonly
setting asserts that the method does not access or modify externally accessible mutable memory. This means the method can access or modify mutable memory for newly allocated objects that is not accessible by other methods or top-level execution before return from the method, but it can not access or modify any mutable global state or mutable memory pointed to by its arguments.
Below is an incomplete list of examples that invalidate this assumption:
getglobal
call to access a mutable global variablesetglobal!
call to perform assignment to a non-constant global variablesetfield!
call that changes a field of a global mutable variableThis:inaccessiblememonly
assertion covers any other methods called by the annotated method.
:noub
The:noub
setting asserts that the method will not execute any undefined behavior (for any input). Note that undefined behavior may technically cause the method to violate any other effect assertions (such as:consistent
or:effect_free
) as well, but we do not model this, and they assume the absence of undefined behavior.
:nortcall
The:nortcall
setting asserts that the method does not callCore.Compiler.return_type
, and that any other methods this method might call also do not callCore.Compiler.return_type
.
To be precise, this assertion can be used when a call toCore.Compiler.return_type
is not made at runtime; that is, when the result ofCore.Compiler.return_type
is known exactly at compile time and the call is eliminated by the optimizer. However, since whether the result ofCore.Compiler.return_type
is folded at compile time depends heavily on the compiler's implementation, it is generally risky to assert this if the method in question usesCore.Compiler.return_type
in any form.
:foldable
This setting is a convenient shortcut for the set of effects that the compiler requires to be guaranteed to constant fold a call at compile time. It is currently equivalent to the followingsetting
s:
:consistent
:effect_free
:terminates_globally
:noub
:nortcall
This list in particular does not include:nothrow
. The compiler will still attempt constant propagation and note any thrown error at compile time. Note however, that by the:consistent
-cy requirements, any such annotated call must consistently throw given the same argument values.
An explicit@inbounds
annotation inside the function will also disable constant folding and not be overridden by:foldable
.
:removable
This setting is a convenient shortcut for the set of effects that the compiler requires to be guaranteed to delete a call whose result is unused at compile time. It is currently equivalent to the followingsetting
s:
:effect_free
:nothrow
:terminates_globally
:total
Thissetting
is the maximum possible set of effects. It currently implies the following othersetting
s:
:consistent
:effect_free
:nothrow
:terminates_globally
:notaskstate
:inaccessiblememonly
:noub
:nortcall
:total
is a very strong assertion and will likely gain additional semantics in future versions of Julia (e.g. if additional effects are added and included in the definition of:total
). As a result, it should be used with care. Whenever possible, prefer to use the minimum possible set of specific effect assertions required for a particular application. In cases where a large number of effect overrides apply to a set of functions, a custom macro is recommended over the use of:total
.
Negated effects
Effect names may be prefixed by!
to indicate that the effect should be removed from an earlier meta effect. For example,:total !:nothrow
indicates that while the call is generally total, it may however throw.
Base.@deprecate
—Macro@deprecate old new [export_old=true]
Deprecate methodold
and specify the replacement callnew
, defining a new methodold
with the specified signature in the process.
To preventold
from being exported, setexport_old
tofalse
.
See alsoBase.depwarn()
.
As of Julia 1.5, functions defined by@deprecate
do not print warning whenjulia
is run without the--depwarn=yes
flag set, as the default value of--depwarn
option isno
. The warnings are printed from tests run byPkg.test()
.
Examples
julia> @deprecate old(x) new(x)old (generic function with 1 method)julia> @deprecate old(x) new(x) falseold (generic function with 1 method)
Calls to@deprecate
without explicit type-annotations will define deprecated methods accepting any number of positional and keyword arguments of typeAny
.
Keyword arguments are forwarded when there is no explicit type annotation as of Julia 1.9. For older versions, you can manually forward positional and keyword arguments by doing@deprecate old(args...; kwargs...) new(args...; kwargs...)
.
To restrict deprecation to a specific signature, annotate the arguments ofold
. For example,
julia> new(x::Int) = x;julia> new(x::Float64) = 2x;julia> @deprecate old(x::Int) new(x);julia> methods(old)# 1 method for generic function "old" from Main: [1] old(x::Int64) @ deprecated.jl:94
will define and deprecate a methodold(x::Int)
that mirrorsnew(x::Int)
but will not define nor deprecate the methodold(x::Float64)
.
Base.depwarn
—FunctionBase.depwarn(msg::String, funcsym::Symbol; force=false)
Printmsg
as a deprecation warning. The symbolfuncsym
should be the name of the calling function, which is used to ensure that the deprecation warning is only printed the first time for each call place. Setforce=true
to force the warning to always be shown, even if Julia was started with--depwarn=no
(the default).
See also@deprecate
.
Examples
function deprecated_func() Base.depwarn("Don't use `deprecated_func()`!", :deprecated_func) 1 + 1end
Base.Missing
—TypeMissing
A type with no fields whose singleton instancemissing
is used to represent missing values.
See also:skipmissing
,nonmissingtype
,Nothing
.
Base.missing
—Constantmissing
The singleton instance of typeMissing
representing a missing value.
See also:NaN
,skipmissing
,nonmissingtype
.
Base.coalesce
—Functioncoalesce(x...)
Return the first value in the arguments which is not equal tomissing
, if any. Otherwise returnmissing
.
See alsoskipmissing
,something
,@coalesce
.
Examples
julia> coalesce(missing, 1)1julia> coalesce(1, missing)1julia> coalesce(nothing, 1) # returns `nothing`julia> coalesce(missing, missing)missing
Base.@coalesce
—Macro@coalesce(x...)
Short-circuiting version ofcoalesce
.
Examples
julia> f(x) = (println("f($x)"); missing);julia> a = 1;julia> a = @coalesce a f(2) f(3) error("`a` is still missing")1julia> b = missing;julia> b = @coalesce b f(2) f(3) error("`b` is still missing")f(2)f(3)ERROR: `b` is still missing[...]
This macro is available as of Julia 1.7.
Base.ismissing
—FunctionBase.skipmissing
—Functionskipmissing(itr)
Return an iterator over the elements initr
skippingmissing
values. The returned object can be indexed using indices ofitr
if the latter is indexable. Indices corresponding to missing values are not valid: they are skipped bykeys
andeachindex
, and aMissingException
is thrown when trying to use them.
Usecollect
to obtain anArray
containing the non-missing
values initr
. Note that even ifitr
is a multidimensional array, the result will always be aVector
since it is not possible to remove missings while preserving dimensions of the input.
See alsocoalesce
,ismissing
,something
.
Examples
julia> x = skipmissing([1, missing, 2])skipmissing(Union{Missing, Int64}[1, missing, 2])julia> sum(x)3julia> x[1]1julia> x[2]ERROR: MissingException: the value at index (2,) is missing[...]julia> argmax(x)3julia> collect(keys(x))2-element Vector{Int64}: 1 3julia> collect(skipmissing([1, missing, 2]))2-element Vector{Int64}: 1 2julia> collect(skipmissing([1 missing; 2 missing]))2-element Vector{Int64}: 1 2
Base.nonmissingtype
—Functionnonmissingtype(T::Type)
IfT
is a union of types containingMissing
, return a new type withMissing
removed.
Examples
julia> nonmissingtype(Union{Int64,Missing})Int64julia> nonmissingtype(Any)Any
This function is exported as of Julia 1.3.
Base.run
—Functionrun(command, args...; wait::Bool = true)
Run a command object, constructed with backticks (see theRunning External Programs section in the manual). Throws an error if anything goes wrong, including the process exiting with a non-zero status (whenwait
is true).
Theargs...
allow you to pass through file descriptors to the command, and are ordered like regular unix file descriptors (egstdin, stdout, stderr, FD(3), FD(4)...
).
Ifwait
is false, the process runs asynchronously. You can later wait for it and check its exit status by callingsuccess
on the returned process object.
Whenwait
is false, the process' I/O streams are directed todevnull
. Whenwait
is true, I/O streams are shared with the parent process. Usepipeline
to control I/O redirection.
Base.devnull
—Constantdevnull
Used in a stream redirect to discard all data written to it. Essentially equivalent to/dev/null
on Unix orNUL
on Windows. Usage:
run(pipeline(`cat test.txt`, devnull))
Base.success
—Functionsuccess(command)
Run a command object, constructed with backticks (see theRunning External Programs section in the manual), and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.
Base.process_running
—Functionprocess_running(p::Process)
Determine whether a process is currently running.
Base.process_exited
—Functionprocess_exited(p::Process)
Determine whether a process has exited.
Base.kill
—Methodkill(p::Process, signum=Base.SIGTERM)
Send a signal to a process. The default is to terminate the process. Returns successfully if the process has already exited, but throws an error if killing the process failed for other reasons (e.g. insufficient permissions).
Base.Sys.set_process_title
—FunctionSys.set_process_title(title::AbstractString)
Set the process title. No-op on some operating systems.
Base.Sys.get_process_title
—FunctionSys.get_process_title()
Get the process title. On some systems, will always return an empty string.
Base.ignorestatus
—Functionignorestatus(command)
Mark a command object so that running it will not throw an error if the result code is non-zero.
Base.detach
—Functiondetach(command)
Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.
Base.Cmd
—TypeCmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)Cmd(exec::Vector{String})
Construct a newCmd
object, representing an external program and arguments, fromcmd
, while changing the settings of the optional keyword arguments:
ignorestatus::Bool
: Iftrue
(defaults tofalse
), then theCmd
will not throw an error if the return code is nonzero.detach::Bool
: Iftrue
(defaults tofalse
), then theCmd
will be run in a new process group, allowing it to outlive thejulia
process and not have Ctrl-C passed to it.windows_verbatim::Bool
: Iftrue
(defaults tofalse
), then on Windows theCmd
will send a command-line string to the process with no quoting or escaping of arguments, even arguments containing spaces. (On Windows, arguments are sent to a program as a single "command-line" string, and programs are responsible for parsing it into arguments. By default, empty arguments and arguments with spaces or tabs are quoted with double quotes"
in the command line, and\
or"
are preceded by backslashes.windows_verbatim=true
is useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.windows_hide::Bool
: Iftrue
(defaults tofalse
), then on Windows no new console window is displayed when theCmd
is executed. This has no effect if a console is already open or on non-Windows systems.env
: Set environment variables to use when running theCmd
.env
is either a dictionary mapping strings to strings, an array of strings of the form"var=val"
, an array or tuple of"var"=>val
pairs. In order to modify (rather than replace) the existing environment, initializeenv
withcopy(ENV)
and then setenv["var"]=val
as desired. To add to an environment block within aCmd
object without replacing all elements, useaddenv()
which will return aCmd
object with the updated environment.dir::AbstractString
: Specify a working directory for the command (instead of the current directory).For any keywords that are not specified, the current settings fromcmd
are used.
Note that theCmd(exec)
constructor does not create a copy ofexec
. Any subsequent changes toexec
will be reflected in theCmd
object.
The most common way to construct aCmd
object is with command literals (backticks), e.g.
`ls -l`
This can then be passed to theCmd
constructor to modify its settings, e.g.
Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)
Base.setenv
—Functionsetenv(command::Cmd, env; dir)
Set environment variables to use when running the givencommand
.env
is either a dictionary mapping strings to strings, an array of strings of the form"var=val"
, or zero or more"var"=>val
pair arguments. In order to modify (rather than replace) the existing environment, createenv
throughcopy(ENV)
and then settingenv["var"]=val
as desired, or useaddenv
.
Thedir
keyword argument can be used to specify a working directory for the command.dir
defaults to the currently setdir
forcommand
(which is the current working directory if not specified already).
Base.addenv
—Functionaddenv(command::Cmd, env...; inherit::Bool = true)
Merge new environment mappings into the givenCmd
object, returning a newCmd
object. Duplicate keys are replaced. Ifcommand
does not contain any environment values set already, it inherits the current environment at time ofaddenv()
call ifinherit
istrue
. Keys with valuenothing
are deleted from the env.
This function requires Julia 1.6 or later.
Base.withenv
—Functionwithenv(f, kv::Pair...)
Executef
in an environment that is temporarily modified (not replaced as insetenv
) by zero or more"var"=>val
argumentskv
.withenv
is generally used via thewithenv(kv...) do ... end
syntax. A value ofnothing
can be used to temporarily unset an environment variable (if it is set). Whenwithenv
returns, the original environment has been restored.
Changing the environment is not thread-safe. For running external commands with a different environment from the parent process, prefer usingaddenv
overwithenv
.
Base.setcpuaffinity
—Functionsetcpuaffinity(original_command::Cmd, cpus) -> command::Cmd
Set the CPU affinity of thecommand
by a list of CPU IDs (1-based)cpus
. Passingcpus = nothing
means to unset the CPU affinity if theoriginal_command
has any.
This function is supported only in Linux and Windows. It is not supported in macOS because libuv does not support affinity setting.
This function requires at least Julia 1.8.
Examples
In Linux, thetaskset
command line program can be used to see howsetcpuaffinity
works.
julia> run(setcpuaffinity(`sh -c 'taskset -p $$'`, [1, 2, 5]));pid 2273's current affinity mask: 13
Note that the mask value13
reflects that the first, second, and the fifth bits (counting from the least significant position) are turned on:
julia> 0b0100110x13
Base.pipeline
—Methodpipeline(from, to, ...)
Create a pipeline from a data source to a destination. The source and destination can be commands, I/O streams, strings, or results of otherpipeline
calls. At least one argument must be a command. Strings refer to filenames. When called with more than two arguments, they are chained together from left to right. For example,pipeline(a,b,c)
is equivalent topipeline(pipeline(a,b),c)
. This provides a more concise way to specify multi-stage pipelines.
Examples:
run(pipeline(`ls`, `grep xyz`))run(pipeline(`ls`, "out.txt"))run(pipeline("out.txt", `grep xyz`))
Base.pipeline
—Methodpipeline(command; stdin, stdout, stderr, append=false)
Redirect I/O to or from the givencommand
. Keyword arguments specify which of the command's streams should be redirected.append
controls whether file output appends to the file. This is a more general version of the 2-argumentpipeline
function.pipeline(from, to)
is equivalent topipeline(from, stdout=to)
whenfrom
is a command, and topipeline(to, stdin=from)
whenfrom
is another kind of data source.
Examples:
run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt"))run(pipeline(`update`, stdout="log.txt", append=true))
Base.Libc.gethostname
—Functiongethostname() -> String
Get the local machine's host name.
Base.Libc.getpid
—Functiongetpid() -> Int32
Get Julia's process ID.
getpid(process) -> Int32
Get the child process ID, if it still exists.
This function requires at least Julia 1.1.
Base.Libc.time
—Methodtime() -> Float64
Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.
Base.time_ns
—Functiontime_ns() -> UInt64
Get the time in nanoseconds relative to some machine-specific arbitrary time in the past. The primary use is for measuring elapsed times during program execution. The return value is guaranteed to be monotonic (mod 2⁶⁴) while the system is running, and is unaffected by clock drift or changes to local calendar time, but it may change arbitrarily across system reboots or suspensions.
(Although the returned time is always in nanoseconds, the timing resolution is platform-dependent.)
Base.@time
—Macro@time expr@time "description" expr
A macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression. Any time spent garbage collecting (gc), compiling new code, or recompiling invalidated code is shown as a percentage. Any lock conflicts where aReentrantLock
had to wait are shown as a count.
Optionally provide a description string to print before the time report.
In some cases the system will look inside the@time
expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run@time @eval ...
.
See also@showtime
,@timev
,@timed
,@elapsed
,@allocated
, and@allocations
.
For more serious benchmarking, consider the@btime
macro from the BenchmarkTools.jl package which among other things evaluates the function multiple times in order to reduce noise.
The option to add a description was introduced in Julia 1.8.
Recompilation time being shown separately from compilation time was introduced in Julia 1.8
The reporting of any lock conflicts was added in Julia 1.11.
julia> x = rand(10,10);julia> @time x * x; 0.606588 seconds (2.19 M allocations: 116.555 MiB, 3.75% gc time, 99.94% compilation time)julia> @time x * x; 0.000009 seconds (1 allocation: 896 bytes)julia> @time begin sleep(0.3) 1+1 end 0.301395 seconds (8 allocations: 336 bytes)2julia> @time "A one second sleep" sleep(1)A one second sleep: 1.005750 seconds (5 allocations: 144 bytes)julia> for loop in 1:3 @time loop sleep(1) end1: 1.006760 seconds (5 allocations: 144 bytes)2: 1.001263 seconds (5 allocations: 144 bytes)3: 1.003676 seconds (5 allocations: 144 bytes)
Base.@showtime
—Macro@showtime expr
Like@time
but also prints the expression being evaluated for reference.
This macro was added in Julia 1.8.
See also@time
.
julia> @showtime sleep(1)sleep(1): 1.002164 seconds (4 allocations: 128 bytes)
Base.@timev
—Macro@timev expr@timev "description" expr
This is a verbose version of the@time
macro. It first prints the same information as@time
, then any non-zero memory allocation counters, and then returns the value of the expression.
Optionally provide a description string to print before the time report.
The option to add a description was introduced in Julia 1.8.
See also@time
,@timed
,@elapsed
,@allocated
, and@allocations
.
julia> x = rand(10,10);julia> @timev x * x; 0.546770 seconds (2.20 M allocations: 116.632 MiB, 4.23% gc time, 99.94% compilation time)elapsed time (ns): 546769547gc time (ns): 23115606bytes allocated: 122297811pool allocs: 2197930non-pool GC allocs:1327malloc() calls: 36realloc() calls: 5GC pauses: 3julia> @timev x * x; 0.000010 seconds (1 allocation: 896 bytes)elapsed time (ns): 9848bytes allocated: 896pool allocs: 1
Base.@timed
—Macro@timed
A macro to execute an expression, and return the value of the expression, elapsed time in seconds, total bytes allocated, garbage collection time, an object with various memory allocation counters, compilation time in seconds, and recompilation time in seconds. Any lock conflicts where aReentrantLock
had to wait are shown as a count.
In some cases the system will look inside the@timed
expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run@timed @eval ...
.
See also@time
,@timev
,@elapsed
,@allocated
,@allocations
, and@lock_conflicts
.
julia> stats = @timed rand(10^6);julia> stats.time0.006634834julia> stats.bytes8000256julia> stats.gctime0.0055765julia> propertynames(stats.gcstats)(:allocd, :malloc, :realloc, :poolalloc, :bigalloc, :freecall, :total_time, :pause, :full_sweep)julia> stats.gcstats.total_time5576500julia> stats.compile_time0.0julia> stats.recompile_time0.0
The return type of this macro was changed fromTuple
toNamedTuple
in Julia 1.5.
Thelock_conflicts
,compile_time
, andrecompile_time
fields were added in Julia 1.11.
Base.@elapsed
—Macro@elapsed
A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.
In some cases the system will look inside the@elapsed
expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run@elapsed @eval ...
.
See also@time
,@timev
,@timed
,@allocated
, and@allocations
.
julia> @elapsed sleep(0.3)0.301391426
Base.@allocated
—Macro@allocated
A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression.
See also@allocations
,@time
,@timev
,@timed
, and@elapsed
.
julia> @allocated rand(10^6)8000080
Base.@allocations
—Macro@allocations
A macro to evaluate an expression, discard the resulting value, and instead return the total number of allocations during evaluation of the expression.
See also@allocated
,@time
,@timev
,@timed
, and@elapsed
.
julia> @allocations rand(10^6)2
This macro was added in Julia 1.9.
Base.@lock_conflicts
—Macro@lock_conflicts
A macro to evaluate an expression, discard the resulting value, and instead return the total number of lock conflicts during evaluation, where a lock attempt on aReentrantLock
resulted in a wait because the lock was already held.
See also@time
,@timev
and@timed
.
julia> @lock_conflicts begin l = ReentrantLock() Threads.@threads for i in 1:Threads.nthreads() lock(l) do sleep(1) end endend5
This macro was added in Julia 1.11.
Base.EnvDict
—TypeEnvDict() -> EnvDict
A singleton of this type provides a hash table interface to environment variables.
Base.ENV
—ConstantENV
Reference to the singletonEnvDict
, providing a dictionary interface to system environment variables.
(On Windows, system environment variables are case-insensitive, andENV
correspondingly converts all keys to uppercase for display, iteration, and copying. Portable code should not rely on the ability to distinguish variables by case, and should beware that setting an ostensibly lowercase variable may result in an uppercaseENV
key.)
Mutating the environment is not thread-safe.
Examples
julia> ENVBase.EnvDict with "50" entries: "SECURITYSESSIONID" => "123" "USER" => "username" "MallocNanoZone" => "0" ⋮ => ⋮julia> ENV["JULIA_EDITOR"] = "vim""vim"julia> ENV["JULIA_EDITOR"]"vim"
Base.Sys.STDLIB
—ConstantSys.STDLIB::String
A string containing the full path to the directory containing thestdlib
packages.
Base.Sys.isunix
—FunctionSys.isunix([os])
Predicate for testing if the OS provides a Unix-like interface. See documentation inHandling Operating System Variation.
Base.Sys.isapple
—FunctionSys.isapple([os])
Predicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. See documentation inHandling Operating System Variation.
Base.Sys.islinux
—FunctionSys.islinux([os])
Predicate for testing if the OS is a derivative of Linux. See documentation inHandling Operating System Variation.
Base.Sys.isbsd
—FunctionSys.isbsd([os])
Predicate for testing if the OS is a derivative of BSD. See documentation inHandling Operating System Variation.
The Darwin kernel descends from BSD, which means thatSys.isbsd()
istrue
on macOS systems. To exclude macOS from a predicate, useSys.isbsd() && !Sys.isapple()
.
Base.Sys.isfreebsd
—FunctionSys.isfreebsd([os])
Predicate for testing if the OS is a derivative of FreeBSD. See documentation inHandling Operating System Variation.
Not to be confused withSys.isbsd()
, which istrue
on FreeBSD but also on other BSD-based systems.Sys.isfreebsd()
refers only to FreeBSD.
This function requires at least Julia 1.1.
Base.Sys.isopenbsd
—FunctionSys.isopenbsd([os])
Predicate for testing if the OS is a derivative of OpenBSD. See documentation inHandling Operating System Variation.
Not to be confused withSys.isbsd()
, which istrue
on OpenBSD but also on other BSD-based systems.Sys.isopenbsd()
refers only to OpenBSD.
This function requires at least Julia 1.1.
Base.Sys.isnetbsd
—FunctionSys.isnetbsd([os])
Predicate for testing if the OS is a derivative of NetBSD. See documentation inHandling Operating System Variation.
Not to be confused withSys.isbsd()
, which istrue
on NetBSD but also on other BSD-based systems.Sys.isnetbsd()
refers only to NetBSD.
This function requires at least Julia 1.1.
Base.Sys.isdragonfly
—FunctionSys.isdragonfly([os])
Predicate for testing if the OS is a derivative of DragonFly BSD. See documentation inHandling Operating System Variation.
Not to be confused withSys.isbsd()
, which istrue
on DragonFly but also on other BSD-based systems.Sys.isdragonfly()
refers only to DragonFly.
This function requires at least Julia 1.1.
Base.Sys.iswindows
—FunctionSys.iswindows([os])
Predicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation inHandling Operating System Variation.
Base.Sys.windows_version
—FunctionSys.windows_version()
Return the version number for the Windows NT Kernel as aVersionNumber
, i.e.v"major.minor.build"
, orv"0.0.0"
if this is not running on Windows.
Base.Sys.free_memory
—FunctionSys.free_memory()
Get the total free memory in RAM in bytes.
Base.Sys.total_memory
—FunctionSys.total_memory()
Get the total memory in RAM (including that which is currently used) in bytes. This amount may be constrained, e.g., by Linux control groups. For the unconstrained amount, seeSys.total_physical_memory()
.
Base.Sys.free_physical_memory
—FunctionSys.free_physical_memory()
Get the free memory of the system in bytes. The entire amount may not be available to the current process; useSys.free_memory()
for the actually available amount.
Base.Sys.total_physical_memory
—FunctionSys.total_physical_memory()
Get the total memory in RAM (including that which is currently used) in bytes. The entire amount may not be available to the current process; seeSys.total_memory()
.
Base.Sys.uptime
—FunctionSys.uptime()
Gets the current system uptime in seconds.
Base.Sys.isjsvm
—FunctionSys.isjsvm([os])
Predicate for testing if Julia is running in a JavaScript VM (JSVM), including e.g. a WebAssembly JavaScript embedding in a web browser.
This function requires at least Julia 1.2.
Base.Sys.loadavg
—FunctionSys.loadavg()
Get the load average. See: https://en.wikipedia.org/wiki/Load_(computing).
Base.Sys.isexecutable
—Functionisexecutable(path::String)
Returntrue
if the givenpath
has executable permissions.
This permission may change before the user executespath
, so it is recommended to execute the file and handle the error if that fails, rather than callingisexecutable
first.
Prior to Julia 1.6, this did not correctly interrogate filesystem ACLs on Windows, therefore it would returntrue
for any file. From Julia 1.6 on, it correctly determines whether the file is marked as executable or not.
See alsoispath
,isreadable
,iswritable
.
Base.Sys.isreadable
—Functionisreadable(path::String)
Returntrue
if the access permissions for the givenpath
permitted reading by the current user.
This permission may change before the user callsopen
, so it is recommended to just callopen
alone and handle the error if that fails, rather than callingisreadable
first.
Currently this function does not correctly interrogate filesystem ACLs on Windows, therefore it can return wrong results.
This function requires at least Julia 1.11.
See alsoispath
,isexecutable
,iswritable
.
isreadable(io) -> Bool
Returnfalse
if the specified IO object is not readable.
Examples
julia> open("myfile.txt", "w") do io print(io, "Hello world!"); isreadable(io) endfalsejulia> open("myfile.txt", "r") do io isreadable(io) endtruejulia> rm("myfile.txt")
Base.Sys.iswritable
—Functioniswritable(path::String)
Returntrue
if the access permissions for the givenpath
permitted writing by the current user.
This permission may change before the user callsopen
, so it is recommended to just callopen
alone and handle the error if that fails, rather than callingiswritable
first.
Currently this function does not correctly interrogate filesystem ACLs on Windows, therefore it can return wrong results.
This function requires at least Julia 1.11.
See alsoispath
,isexecutable
,isreadable
.
iswritable(io) -> Bool
Returnfalse
if the specified IO object is not writable.
Examples
julia> open("myfile.txt", "w") do io print(io, "Hello world!"); iswritable(io) endtruejulia> open("myfile.txt", "r") do io iswritable(io) endfalsejulia> rm("myfile.txt")
Base.Sys.username
—FunctionSys.username() -> String
Return the username for the current user. If the username cannot be determined or is empty, this function throws an error.
To retrieve a username that is overridable via an environment variable, e.g.,USER
, consider using
user = get(Sys.username, ENV, "USER")
This function requires at least Julia 1.11.
See alsohomedir
.
Base.@static
—Macro@static
Partially evaluate an expression at parse time.
For example,@static Sys.iswindows() ? foo : bar
will evaluateSys.iswindows()
and insert eitherfoo
orbar
into the expression. This is useful in cases where a construct would be invalid on other platforms, such as accall
to a non-existent function.@static if Sys.isapple() foo end
and@static foo <&&,||> bar
are also valid syntax.
Base.VersionNumber
—TypeVersionNumber
Version number type which follows the specifications ofsemantic versioning (semver), composed of major, minor and patch numeric values, followed by pre-release and build alphanumeric annotations.
VersionNumber
objects can be compared with all of the standard comparison operators (==
,<
,<=
, etc.), with the result following semver rules.
VersionNumber
has the the following public fields:
v.major::Integer
v.minor::Integer
v.patch::Integer
v.prerelease::Tuple{Vararg{Union{Integer, AbstractString}}}
v.build::Tuple{Vararg{Union{Integer, AbstractString}}}
See also@v_str
to efficiently constructVersionNumber
objects from semver-format literal strings,VERSION
for theVersionNumber
of Julia itself, andVersion Number Literals in the manual.
Examples
julia> a = VersionNumber(1, 2, 3)v"1.2.3"julia> a >= v"1.2"truejulia> b = VersionNumber("2.0.1-rc1")v"2.0.1-rc1"julia> b >= v"2.0.1"false
Base.@v_str
—Macro@v_str
String macro used to parse a string to aVersionNumber
.
Examples
julia> v"1.2.3"v"1.2.3"julia> v"2.0.1-rc1"v"2.0.1-rc1"
Base.error
—Functionerror(message::AbstractString)
Raise anErrorException
with the given message.
error(msg...)
Raise anErrorException
with a message constructed bystring(msg...)
.
Core.throw
—FunctionBase.rethrow
—Functionrethrow()
Rethrow the current exception from within acatch
block. The rethrown exception will continue propagation as if it had not been caught.
The alternative formrethrow(e)
allows you to associate an alternative exception objecte
with the current backtrace. However this misrepresents the program state at the time of the error so you're encouraged to instead throw a new exception usingthrow(e)
. In Julia 1.1 and above, usingthrow(e)
will preserve the root cause exception on the stack, as described incurrent_exceptions
.
Base.backtrace
—Functionbacktrace()
Get a backtrace object for the current program point.
Base.catch_backtrace
—Functioncatch_backtrace()
Get the backtrace of the current exception, for use withincatch
blocks.
Base.current_exceptions
—Functioncurrent_exceptions(task::Task=current_task(); [backtrace::Bool=true])
Get the stack of exceptions currently being handled. For nested catch blocks there may be more than one current exception in which case the most recently thrown exception is last in the stack. The stack is returned as anExceptionStack
which is an AbstractVector of named tuples(exception,backtrace)
. Ifbacktrace
is false, the backtrace in each pair will be set tonothing
.
Explicitly passingtask
will return the current exception stack on an arbitrary task. This is useful for inspecting tasks which have failed due to uncaught exceptions.
This function went by the experimental namecatch_stack()
in Julia 1.1–1.6, and had a plain Vector-of-tuples as a return type.
Base.@assert
—Macro@assert cond [text]
Throw anAssertionError
ifcond
isfalse
. This is the preferred syntax for writing assertions, which are conditions that are assumed to be true, but that the user might decide to check anyways, as an aid to debugging if they fail. The optional messagetext
is displayed upon assertion failure.
An assert might be disabled at some optimization levels. Assert should therefore only be used as a debugging tool and not used for authentication verification (e.g., verifying passwords or checking array bounds). The code must not rely on the side effects of runningcond
for the correct behavior of a function.
Examples
julia> @assert iseven(3) "3 is an odd number!"ERROR: AssertionError: 3 is an odd number!julia> @assert isodd(3) "What even are numbers?"
Base.Experimental.register_error_hint
—FunctionExperimental.register_error_hint(handler, exceptiontype)
Register a "hinting" functionhandler(io, exception)
that can suggest potential ways for users to circumvent errors.handler
should examineexception
to see whether the conditions appropriate for a hint are met, and if so generate output toio
. Packages should callregister_error_hint
from within their__init__
function.
For specific exception types,handler
is required to accept additional arguments:
MethodError
: providehandler(io, exc::MethodError, argtypes, kwargs)
, which splits the combined arguments into positional and keyword arguments.When issuing a hint, the output should typically start with\n
.
If you define custom exception types, yourshowerror
method can support hints by callingExperimental.show_error_hints
.
Examples
julia> module Hinter only_int(x::Int) = 1 any_number(x::Number) = 2 function __init__() Base.Experimental.register_error_hint(MethodError) do io, exc, argtypes, kwargs if exc.f == only_int # Color is not necessary, this is just to show it's possible. print(io, "\nDid you mean to call ") printstyled(io, "`any_number`?", color=:cyan) end end end end
Then if you callHinter.only_int
on something that isn't anInt
(thereby triggering aMethodError
), it issues the hint:
julia> Hinter.only_int(1.0)ERROR: MethodError: no method matching only_int(::Float64)The function `only_int` exists, but no method is defined for this combination of argument types.Did you mean to call `any_number`?Closest candidates are: ...
Custom error hints are available as of Julia 1.5.
This interface is experimental and subject to change or removal without notice. To insulate yourself against changes, consider putting any registrations inside anif isdefined(Base.Experimental, :register_error_hint) ... end
block.
Base.Experimental.show_error_hints
—FunctionExperimental.show_error_hints(io, ex, args...)
Invoke all handlers fromExperimental.register_error_hint
for the particular exception typetypeof(ex)
.args
must contain any other arguments expected by the handler for that type.
Custom error hints are available as of Julia 1.5.
This interface is experimental and subject to change or removal without notice.
Core.ArgumentError
—TypeArgumentError(msg)
The arguments passed to a function are invalid.msg
is a descriptive error message.
Core.AssertionError
—TypeAssertionError([msg])
The asserted condition did not evaluate totrue
. Optional argumentmsg
is a descriptive error string.
Examples
julia> @assert false "this is not true"ERROR: AssertionError: this is not true
AssertionError
is usually thrown from@assert
.
Core.BoundsError
—TypeBoundsError([a],[i])
An indexing operation into an array,a
, tried to access an out-of-bounds element at indexi
.
Examples
julia> A = fill(1.0, 7);julia> A[8]ERROR: BoundsError: attempt to access 7-element Vector{Float64} at index [8]julia> B = fill(1.0, (2,3));julia> B[2, 4]ERROR: BoundsError: attempt to access 2×3 Matrix{Float64} at index [2, 4]julia> B[9]ERROR: BoundsError: attempt to access 2×3 Matrix{Float64} at index [9]
Base.CompositeException
—TypeCompositeException
Wrap aVector
of exceptions thrown by aTask
(e.g. generated from a remote worker over a channel or an asynchronously executing local I/O write or a remote worker underpmap
) with information about the series of exceptions. For example, if a group of workers are executing several tasks, and multiple workers fail, the resultingCompositeException
will contain a "bundle" of information from each worker indicating where and why the exception(s) occurred.
Base.DimensionMismatch
—TypeDimensionMismatch([msg])
The objects called do not have matching dimensionality. Optional argumentmsg
is a descriptive error string.
Core.DivideError
—TypeDivideError()
Integer division was attempted with a denominator value of 0.
Examples
julia> 2/0Infjulia> div(2, 0)ERROR: DivideError: integer division errorStacktrace:[...]
Core.DomainError
—TypeDomainError(val)DomainError(val, msg)
The argumentval
to a function or constructor is outside the valid domain.
Examples
julia> sqrt(-1)ERROR: DomainError with -1.0:sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).Stacktrace:[...]
Base.EOFError
—TypeEOFError()
No more data was available to read from a file or stream.
Core.ErrorException
—TypeErrorException(msg)
Generic error type. The error message, in the.msg
field, may provide more specific details.
Examples
julia> ex = ErrorException("I've done a bad thing");julia> ex.msg"I've done a bad thing"
Core.InexactError
—TypeInexactError(name::Symbol, T, val)
Cannot exactly convertval
to typeT
in a method of functionname
.
Examples
julia> convert(Float64, 1+2im)ERROR: InexactError: Float64(1 + 2im)Stacktrace:[...]
Core.InterruptException
—TypeInterruptException()
The process was stopped by a terminal interrupt (CTRL+C).
Note that, in Julia script started without-i
(interactive) option,InterruptException
is not thrown by default. CallingBase.exit_on_sigint(false)
in the script can recover the behavior of the REPL. Alternatively, a Julia script can be started with
julia -e "include(popfirst!(ARGS))" script.jl
to letInterruptException
be thrown by CTRL+C during the execution.
Base.KeyError
—TypeKeyError(key)
An indexing operation into anAbstractDict
(Dict
) orSet
like object tried to access or delete a non-existent element.
Core.LoadError
—TypeLoadError(file::AbstractString, line::Int, error)
An error occurred whileinclude
ing,require
ing, orusing
a file. The error specifics should be available in the.error
field.
LoadErrors are no longer emitted by@macroexpand
,@macroexpand1
, andmacroexpand
as of Julia 1.7.
Core.MethodError
—TypeMethodError(f, args)
A method with the required type signature does not exist in the given generic function. Alternatively, there is no unique most-specific method.
Base.MissingException
—TypeMissingException(msg)
Exception thrown when amissing
value is encountered in a situation where it is not supported. The error message, in themsg
field may provide more specific details.
Core.OutOfMemoryError
—TypeOutOfMemoryError()
An operation allocated too much memory for either the system or the garbage collector to handle properly.
Core.ReadOnlyMemoryError
—TypeReadOnlyMemoryError()
An operation tried to write to memory that is read-only.
Core.OverflowError
—TypeOverflowError(msg)
The result of an expression is too large for the specified type and will cause a wraparound.
Base.ProcessFailedException
—TypeProcessFailedException
Indicates problematic exit status of a process. When running commands or pipelines, this is thrown to indicate a nonzero exit code was returned (i.e. that the invoked process failed).
Base.TaskFailedException
—TypeTaskFailedException
This exception is thrown by await(t)
call when taskt
fails.TaskFailedException
wraps the failed taskt
.
Core.StackOverflowError
—TypeStackOverflowError()
The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.
Base.SystemError
—TypeSystemError(prefix::AbstractString, [errno::Int32])
A system call failed with an error code (in theerrno
global variable).
Core.TypeError
—TypeTypeError(func::Symbol, context::AbstractString, expected::Type, got)
A type assertion failure, or calling an intrinsic function with an incorrect argument type.
Core.UndefKeywordError
—TypeUndefKeywordError(var::Symbol)
The required keyword argumentvar
was not assigned in a function call.
Examples
julia> function my_func(;my_arg) return my_arg + 1 endmy_func (generic function with 1 method)julia> my_func()ERROR: UndefKeywordError: keyword argument `my_arg` not assignedStacktrace: [1] my_func() at ./REPL[1]:2 [2] top-level scope at REPL[2]:1
Core.UndefRefError
—TypeUndefRefError()
The item or field is not defined for the given object.
Examples
julia> struct MyType a::Vector{Int} MyType() = new() endjulia> A = MyType()MyType(#undef)julia> A.aERROR: UndefRefError: access to undefined referenceStacktrace:[...]
Core.UndefVarError
—TypeUndefVarError(var::Symbol, [scope])
A symbol in the current scope is not defined.
Examples
julia> aERROR: UndefVarError: `a` not defined in `Main`julia> a = 1;julia> a1
Base.StringIndexError
—TypeStringIndexError(str, i)
An error occurred when trying to accessstr
at indexi
that is not valid.
Core.InitError
—TypeInitError(mod::Symbol, error)
An error occurred when running a module's__init__
function. The actual error thrown is available in the.error
field.
Base.retry
—Functionretry(f; delays=ExponentialBackOff(), check=nothing) -> Function
Return an anonymous function that calls functionf
. If an exception arises,f
is repeatedly called again, each timecheck
returnstrue
, after waiting the number of seconds specified indelays
.check
should inputdelays
's current state and theException
.
Before Julia 1.2 this signature was restricted tof::Function
.
Examples
retry(f, delays=fill(5.0, 3))retry(f, delays=rand(5:10, 2))retry(f, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))retry(http_get, check=(s,e)->e.status == "503")(url)retry(read, check=(s,e)->isa(e, IOError))(io, 128; all=false)
Base.ExponentialBackOff
—TypeExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)
AFloat64
iterator of lengthn
whose elements exponentially increase at a rate in the intervalfactor
* (1 ±jitter
). The first element isfirst_delay
and all elements are clamped tomax_delay
.
Base.Timer
—MethodTimer(callback::Function, delay; interval = 0)
Create a timer that runs the functioncallback
at each timer expiration.
Waiting tasks are woken and the functioncallback
is called after an initial delay ofdelay
seconds, and then repeating with the giveninterval
in seconds. Ifinterval
is equal to0
, the callback is only run once. The functioncallback
is called with a single argument, the timer itself. Stop a timer by callingclose
. Thecallback
may still be run one final time, if the timer has already expired.
Examples
Here the first number is printed after a delay of two seconds, then the following numbers are printed quickly.
julia> begin i = 0 cb(timer) = (global i += 1; println(i)) t = Timer(cb, 2, interval=0.2) wait(t) sleep(0.5) close(t) end123
Base.Timer
—TypeTimer(delay; interval = 0)
Create a timer that wakes up tasks waiting for it (by callingwait
on the timer object).
Waiting tasks are woken after an initial delay of at leastdelay
seconds, and then repeating after at leastinterval
seconds again elapse. Ifinterval
is equal to0
, the timer is only triggered once. When the timer is closed (byclose
) waiting tasks are woken with an error. Useisopen
to check whether a timer is still active.
interval
is subject to accumulating time skew. If you need precise events at a particular absolute time, create a new timer at each expiration with the difference to the next time computed.
ATimer
requires yield points to update its state. For instance,isopen(t::Timer)
cannot be used to timeout a non-yielding while loop.
Base.AsyncCondition
—TypeAsyncCondition()
Create a async condition that wakes up tasks waiting for it (by callingwait
on the object) when notified from C by a call touv_async_send
. Waiting tasks are woken with an error when the object is closed (byclose
). Useisopen
to check whether it is still active.
This provides an implicit acquire & release memory ordering between the sending and waiting threads.
Base.AsyncCondition
—MethodAsyncCondition(callback::Function)
Create a async condition that calls the givencallback
function. Thecallback
is passed one argument, the async condition object itself.
Base.nameof
—Methodnameof(m::Module) -> Symbol
Get the name of aModule
as aSymbol
.
Examples
julia> nameof(Base.Broadcast):Broadcast
Base.parentmodule
—Functionparentmodule(m::Module) -> Module
Get a module's enclosingModule
.Main
is its own parent.
See also:names
,nameof
,fullname
,@__MODULE__
.
Examples
julia> parentmodule(Main)Mainjulia> parentmodule(Base.Broadcast)Base
parentmodule(t::DataType) -> Module
Determine the module containing the definition of a (potentiallyUnionAll
-wrapped)DataType
.
Examples
julia> module Foo struct Int end endFoojulia> parentmodule(Int)Corejulia> parentmodule(Foo.Int)Foo
parentmodule(f::Function) -> Module
Determine the module containing the (first) definition of a generic function.
parentmodule(f::Function, types) -> Module
Determine the module containing the first method of a generic functionf
matching the specifiedtypes
.
parentmodule(m::Method) -> Module
Return the module in which the given methodm
is defined.
Passing aMethod
as an argument requires Julia 1.9 or later.
Base.pathof
—Methodpathof(m::Module)
Return the path of them.jl
file that was used toimport
modulem
, ornothing
ifm
was not imported from a package.
Usedirname
to get the directory part andbasename
to get the file name part of the path.
See alsopkgdir
.
Base.pkgdir
—Methodpkgdir(m::Module[, paths::String...])
Return the root directory of the package that declared modulem
, ornothing
ifm
was not declared in a package. Optionally further path component strings can be provided to construct a path within the package root.
To get the root directory of the package that implements the current module the formpkgdir(@__MODULE__)
can be used.
If an extension module is given, the root of the parent package is returned.
julia> pkgdir(Foo)"/path/to/Foo.jl"julia> pkgdir(Foo, "src", "file.jl")"/path/to/Foo.jl/src/file.jl"
See alsopathof
.
The optional argumentpaths
requires at least Julia 1.7.
Base.pkgversion
—Methodpkgversion(m::Module)
Return the version of the package that imported modulem
, ornothing
ifm
was not imported from a package, or imported from a package without a version field set.
The version is read from the package's Project.toml during package load.
To get the version of the package that imported the current module the formpkgversion(@__MODULE__)
can be used.
This function was introduced in Julia 1.9.
Base.moduleroot
—Functionmoduleroot(m::Module) -> Module
Find the root module of a given module. This is the first module in the chain of parent modules ofm
which is either a registered root module or which is its own parent module.
__module__
—Keyword__module__
The argument__module__
is only visible inside the macro, and it provides information (in the form of aModule
object) about the expansion context of the macro invocation. See the manual section onMacro invocation for more information.
__source__
—Keyword__source__
The argument__source__
is only visible inside the macro, and it provides information (in the form of aLineNumberNode
object) about the parser location of the@
sign from the macro invocation. See the manual section onMacro invocation for more information.
Base.@__MODULE__
—Macro@__MODULE__ -> Module
Get theModule
of the toplevel eval, which is theModule
code is currently being read from.
Base.@__FILE__
—Macro@__FILE__ -> String
Expand to a string with the path to the file containing the macrocall, or an empty string if evaluated byjulia -e <expr>
. Returnnothing
if the macro was missing parser source information. Alternatively seePROGRAM_FILE
.
Base.@__DIR__
—Macro@__DIR__ -> String
Macro to obtain the absolute path of the current directory as a string.
If in a script, returns the directory of the script containing the@__DIR__
macrocall. If run from a REPL or if evaluated byjulia -e <expr>
, returns the current working directory.
Examples
The example illustrates the difference in the behaviors of@__DIR__
andpwd()
, by creating a simple script in a different directory than the current working one and executing both commands:
julia> cd("/home/JuliaUser") # working directoryjulia> # create script at /home/JuliaUser/Projects open("/home/JuliaUser/Projects/test.jl","w") do io print(io, """ println("@__DIR__ = ", @__DIR__) println("pwd() = ", pwd()) """) endjulia> # outputs script directory and current working directory include("/home/JuliaUser/Projects/test.jl")@__DIR__ = /home/JuliaUser/Projectspwd() = /home/JuliaUser
Base.@__LINE__
—Macro@__LINE__ -> Int
Expand to the line number of the location of the macrocall. Return0
if the line number could not be determined.
Base.fullname
—Functionfullname(m::Module)
Get the fully-qualified name of a module as a tuple of symbols. For example,
Examples
julia> fullname(Base.Iterators)(:Base, :Iterators)julia> fullname(Main)(:Main,)
Base.names
—Functionnames(x::Module; all::Bool = false, imported::Bool = false)
Get a vector of the public names of aModule
, excluding deprecated names. Ifall
is true, then the list also includes non-public names defined in the module, deprecated names, and compiler-generated names. Ifimported
is true, then names explicitly imported from other modules are also included. Names are returned in sorted order.
As a special case, all names defined inMain
are considered "public", since it is not idiomatic to explicitly mark names fromMain
as public.
sym ∈ names(SomeModule)
doesnot implyisdefined(SomeModule, sym)
.names
will return symbols marked withpublic
orexport
, even if they are not defined in the module.
See also:Base.isexported
,Base.ispublic
,Base.@locals
,@__MODULE__
.
Base.isexported
—Functionisexported(m::Module, s::Symbol) -> Bool
Returns whether a symbol is exported from a module.
julia> module Mod export foo public bar endModjulia> Base.isexported(Mod, :foo)truejulia> Base.isexported(Mod, :bar)falsejulia> Base.isexported(Mod, :baz)false
Base.ispublic
—Functionispublic(m::Module, s::Symbol) -> Bool
Returns whether a symbol is marked as public in a module.
Exported symbols are considered public.
This function and the notion of publicity were added in Julia 1.11.
See also:isexported
,names
julia> module Mod export foo public bar endModjulia> Base.ispublic(Mod, :foo)truejulia> Base.ispublic(Mod, :bar)truejulia> Base.ispublic(Mod, :baz)false
Base.nameof
—Methodnameof(f::Function) -> Symbol
Get the name of a genericFunction
as a symbol. For anonymous functions, this is a compiler-generated name. For explicitly-declared subtypes ofFunction
, it is the name of the function's type.
Base.functionloc
—Methodfunctionloc(f::Function, types)
Return a tuple(filename,line)
giving the location of a genericFunction
definition.
Base.functionloc
—Methodfunctionloc(m::Method)
Return a tuple(filename,line)
giving the location of aMethod
definition.
Base.@locals
—Macro@locals()
Construct a dictionary of the names (as symbols) and values of all local variables defined as of the call site.
This macro requires at least Julia 1.1.
Examples
julia> let x = 1, y = 2 Base.@locals endDict{Symbol, Any} with 2 entries: :y => 2 :x => 1julia> function f(x) local y show(Base.@locals); println() for i = 1:1 show(Base.@locals); println() end y = 2 show(Base.@locals); println() nothing end;julia> f(42)Dict{Symbol, Any}(:x => 42)Dict{Symbol, Any}(:i => 1, :x => 42)Dict{Symbol, Any}(:y => 2, :x => 42)
Core.getglobal
—Functiongetglobal(module::Module, name::Symbol, [order::Symbol=:monotonic])
Retrieve the value of the bindingname
from the modulemodule
. Optionally, an atomic ordering can be defined for the operation, otherwise it defaults to monotonic.
While accessing module bindings usinggetfield
is still supported to maintain compatibility, usinggetglobal
should always be preferred sincegetglobal
allows for control over atomic ordering (getfield
is always monotonic) and better signifies the code's intent both to the user as well as the compiler.
Most users should not have to call this function directly – Thegetproperty
function or corresponding syntax (i.e.module.name
) should be preferred in all but few very specific use cases.
This function requires Julia 1.9 or later.
See alsogetproperty
andsetglobal!
.
Examples
julia> a = 11julia> module M a = 2 end;julia> getglobal(@__MODULE__, :a)1julia> getglobal(M, :a)2
Core.setglobal!
—Functionsetglobal!(module::Module, name::Symbol, x, [order::Symbol=:monotonic])
Set or change the value of the bindingname
in the modulemodule
tox
. No type conversion is performed, so if a type has already been declared for the binding,x
must be of appropriate type or an error is thrown.
Additionally, an atomic ordering can be specified for this operation, otherwise it defaults to monotonic.
Users will typically access this functionality through thesetproperty!
function or corresponding syntax (i.e.module.name = x
) instead, so this is intended only for very specific use cases.
This function requires Julia 1.9 or later.
See alsosetproperty!
andgetglobal
Examples
julia> module M; global a; end;julia> M.a # same as `getglobal(M, :a)`ERROR: UndefVarError: `a` not defined in `M`Suggestion: add an appropriate import or assignment. This global was declared but not assigned.Stacktrace: [1] getproperty(x::Module, f::Symbol) @ Base ./Base.jl:42 [2] top-level scope @ none:1julia> setglobal!(M, :a, 1)1julia> M.a1
Core.modifyglobal!
—Functionmodifyglobal!(module::Module, name::Symbol, op, x, [order::Symbol=:monotonic]) -> Pair
Atomically perform the operations to get and set a global after applying the functionop
.
This function requires Julia 1.11 or later.
See alsomodifyproperty!
andsetglobal!
.
Core.swapglobal!
—Functionswapglobal!(module::Module, name::Symbol, x, [order::Symbol=:monotonic])
Atomically perform the operations to simultaneously get and set a global.
This function requires Julia 1.11 or later.
See alsoswapproperty!
andsetglobal!
.
Core.setglobalonce!
—Functionsetglobalonce!(module::Module, name::Symbol, value, [success_order::Symbol, [fail_order::Symbol=success_order]) -> success::Bool
Atomically perform the operations to set a global to a given value, only if it was previously not set.
This function requires Julia 1.11 or later.
See alsosetpropertyonce!
andsetglobal!
.
Core.replaceglobal!
—Functionreplaceglobal!(module::Module, name::Symbol, expected, desired, [success_order::Symbol, [fail_order::Symbol=success_order]) -> (; old, success::Bool)
Atomically perform the operations to get and conditionally set a global to a given value.
This function requires Julia 1.11 or later.
See alsoreplaceproperty!
andsetglobal!
.
(See also thedocumentation chapter.)
Core.@doc
—MacroDocumentation
Functions, methods and types can be documented by placing a string before the definition:
"""# The Foo Function`foo(x)`: Foo the living hell out of `x`."""foo(x) = ...
The@doc
macro can be used directly to both set and retrieve documentation / metadata. The macro has special parsing so that the documented object may occur on the next line:
@doc "blah"function foo() ...
By default, documentation is written as Markdown, but any object can be used as the first argument.
Documenting objects separately from their definitions
You can document an object before or after its definition with
@doc "foo" function_to_doc@doc "bar" TypeToDoc
For macros, the syntax is@doc "macro doc" :(Module.@macro)
or@doc "macro doc" :(string_macro"")
for string macros. Without the quote:()
the expansion of the macro will be documented.
Retrieving Documentation
You can retrieve docs for functions, macros and other objects as follows:
@doc foo@doc @time@doc md""
Functions & Methods
Placing documentation before a method definition (e.g.function foo() ...
orfoo() = ...
) will cause that specific method to be documented, as opposed to the whole function. Method docs are concatenated together in the order they were defined to provide docs for the function.
Base.Docs.HTML
—TypeHTML(s)
: Create an object that renderss
as html.
HTML("<div>foo</div>")
You can also use a stream for large amounts of data:
HTML() do io println(io, "<div>foo</div>")end
HTML
is currently exported to maintain backwards compatibility, but this export is deprecated. It is recommended to use this type asDocs.HTML
or to explicitly import it fromDocs
.
Base.Docs.Text
—TypeText(s)
: Create an object that renderss
as plain text.
Text("foo")
You can also use a stream for large amounts of data:
Text() do io println(io, "foo")end
Text
is currently exported to maintain backwards compatibility, but this export is deprecated. It is recommended to use this type asDocs.Text
or to explicitly import it fromDocs
.
Base.Docs.hasdoc
—FunctionDocs.hasdoc(mod::Module, sym::Symbol)::Bool
Returntrue
ifsym
inmod
has a docstring andfalse
otherwise.
Base.Docs.undocumented_names
—Functionundocumented_names(mod::Module; private=false)
Return a sorted vector of undocumented symbols inmodule
(that is, lacking docstrings).private=false
(the default) returns only identifiers declared withpublic
and/orexport
, whereasprivate=true
returns all symbols in the module (excluding compiler-generated hidden symbols starting with#
).
See also:names
,Docs.hasdoc
,Base.ispublic
.
Base.identify_package
—FunctionBase.identify_package(name::String)::Union{PkgId, Nothing}Base.identify_package(where::Union{Module,PkgId}, name::String)::Union{PkgId, Nothing}
Identify the package by its name from the current environment stack, returning itsPkgId
, ornothing
if it cannot be found.
If only thename
argument is provided, it searches each environment in the stack and its named direct dependencies.
Thewhere
argument provides the context from where to search for the package: in this case it first checks if the name matches the context itself, otherwise it searches all recursive dependencies (from the resolved manifest of each environment) until it locates the contextwhere
, and from there identifies the dependency with the corresponding name.
julia> Base.identify_package("Pkg") # Pkg is a dependency of the default environmentPkg [44cfe95a-1eb2-52ea-b672-e2afdf69b78f]julia> using LinearAlgebrajulia> Base.identify_package(LinearAlgebra, "Pkg") # Pkg is not a dependency of LinearAlgebra
Base.locate_package
—FunctionBase.locate_package(pkg::PkgId)::Union{String, Nothing}
The path to the entry-point file for the package corresponding to the identifierpkg
, ornothing
if not found. See alsoidentify_package
.
julia> pkg = Base.identify_package("Pkg")Pkg [44cfe95a-1eb2-52ea-b672-e2afdf69b78f]julia> Base.locate_package(pkg)"/path/to/julia/stdlib/v1.11/Pkg/src/Pkg.jl"
Base.require
—Functionrequire(into::Module, module::Symbol)
This function is part of the implementation ofusing
/import
, if a module is not already defined inMain
. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).
Loads a source file, in the context of theMain
module, on every active node, searching standard locations for files.require
is considered a top-level operation, so it sets the currentinclude
path but does not use it to search for files (see help forinclude
). This function is typically used to load library code, and is implicitly called byusing
to load packages.
When searching for files,require
first looks for package code in the global arrayLOAD_PATH
.require
is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.
For more details regarding code loading, see the manual sections onmodules andparallel computing.
Base.compilecache
—FunctionBase.compilecache(module::PkgId)
Creates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored inDEPOT_PATH[1]/compiled
. SeeModule initialization and precompilation for important notes.
Base.isprecompiled
—FunctionBase.isprecompiled(pkg::PkgId; ignore_loaded::Bool=false)
Returns whether a given PkgId within the active project is precompiled.
By default this check observes the same approach that code loading takes with respect to when different versions of dependencies are currently loaded to that which is expected. To ignore loaded modules and answer as if in a fresh julia session specifyignore_loaded=true
.
This function requires at least Julia 1.10.
Base.get_extension
—Functionget_extension(parent::Module, extension::Symbol)
Return the module forextension
ofparent
or returnnothing
if the extension is not loaded.
Base.GC.gc
—FunctionGC.gc([full=true])
Perform garbage collection. The argumentfull
determines the kind of collection: a full collection (default) traverses all live objects (i.e. full mark) and should reclaim memory from all unreachable objects. An incremental collection only reclaims memory from young objects which are not reachable.
The GC may decide to perform a full collection even if an incremental collection was requested.
Excessive use will likely lead to poor performance.
Base.GC.enable
—FunctionGC.enable(on::Bool)
Control whether garbage collection is enabled using a boolean argument (true
for enabled,false
for disabled). Return previous GC state.
Disabling garbage collection should be used only with caution, as it can cause memory use to grow without bound.
Base.GC.@preserve
—MacroGC.@preserve x1 x2 ... xn expr
Mark the objectsx1, x2, ...
as beingin use during the evaluation of the expressionexpr
. This is only required in unsafe code whereexpr
implicitly uses memory or other resources owned by one of thex
s.
Implicit use ofx
covers any indirect use of resources logically owned byx
which the compiler cannot see. Some examples:
Ptr
x
toccall
x
which would be cleaned up in the finalizer.@preserve
should generally not have any performance impact in typical use cases where it briefly extends object lifetime. In implementation,@preserve
has effects such as protecting dynamically allocated objects from garbage collection.
Examples
When loading from a pointer withunsafe_load
, the underlying object is implicitly used, for examplex
is implicitly used byunsafe_load(p)
in the following:
julia> let x = Ref{Int}(101) p = Base.unsafe_convert(Ptr{Int}, x) GC.@preserve x unsafe_load(p) end101
When passing pointers toccall
, the pointed-to object is implicitly used and should be preserved. (Note however that you should normally just passx
directly toccall
which counts as an explicit use.)
julia> let x = "Hello" p = pointer(x) Int(GC.@preserve x @ccall strlen(p::Cstring)::Csize_t) # Preferred alternative Int(@ccall strlen(x::Cstring)::Csize_t) end5
Base.GC.safepoint
—FunctionGC.safepoint()
Inserts a point in the program where garbage collection may run. This can be useful in rare cases in multi-threaded programs where some threads are allocating memory (and hence may need to run GC) but other threads are doing only simple operations (no allocation, task switches, or I/O). Calling this function periodically in non-allocating threads allows garbage collection to run.
This function is available as of Julia 1.4.
Base.GC.enable_logging
—FunctionGC.enable_logging(on::Bool)
When turned on, print statistics about each GC to stderr.
Base.GC.logging_enabled
—FunctionGC.logging_enabled()
Return whether GC logging has been enabled viaGC.enable_logging
.
Base.Meta.lower
—Functionlower(m, x)
Takes the expressionx
and returns an equivalent expression in lowered form for executing in modulem
. See alsocode_lowered
.
Base.Meta.@lower
—Macro@lower [m] x
Return lowered form of the expressionx
in modulem
. By defaultm
is the module in which the macro is called. See alsolower
.
Base.Meta.parse
—Methodparse(str, start; greedy=true, raise=true, depwarn=true, filename="none")
Parse the expression string and return an expression (which could later be passed to eval for execution).start
is the code unit index intostr
of the first character to start parsing at (as with all string indexing, these are not character indices). Ifgreedy
istrue
(default),parse
will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will returnExpr(:incomplete, "(error message)")
. Ifraise
istrue
(default), syntax errors other than incomplete expressions will raise an error. Ifraise
isfalse
,parse
will return an expression that will raise an error upon evaluation. Ifdepwarn
isfalse
, deprecation warnings will be suppressed. Thefilename
argument is used to display diagnostics when an error is raised.
julia> Meta.parse("(α, β) = 3, 5", 1) # start of string(:((α, β) = (3, 5)), 16)julia> Meta.parse("(α, β) = 3, 5", 1, greedy=false)(:((α, β)), 9)julia> Meta.parse("(α, β) = 3, 5", 16) # end of string(nothing, 16)julia> Meta.parse("(α, β) = 3, 5", 11) # index of 3(:((3, 5)), 16)julia> Meta.parse("(α, β) = 3, 5", 11, greedy=false)(3, 13)
Base.Meta.parse
—Methodparse(str; raise=true, depwarn=true, filename="none")
Parse the expression string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. Ifraise
istrue
(default), syntax errors will raise an error; otherwise,parse
will return an expression that will raise an error upon evaluation. Ifdepwarn
isfalse
, deprecation warnings will be suppressed. Thefilename
argument is used to display diagnostics when an error is raised.
julia> Meta.parse("x = 3"):(x = 3)julia> Meta.parse("1.0.2")ERROR: ParseError:# Error @ none:1:11.0.2└──┘ ── invalid numeric constant[...]julia> Meta.parse("1.0.2"; raise = false):($(Expr(:error, "invalid numeric constant "1.0."")))julia> Meta.parse("x = "):($(Expr(:incomplete, "incomplete: premature end of input")))
Base.Meta.ParseError
—TypeParseError(msg)
The expression passed to theparse
function could not be interpreted as a valid Julia expression.
Core.QuoteNode
—TypeQuoteNode
A quoted piece of code, that does not support interpolation. See themanual section about QuoteNodes for details.
Base.macroexpand
—Functionmacroexpand(m::Module, x; recursive=true)
Take the expressionx
and return an equivalent expression with all macros removed (expanded) for executing in modulem
. Therecursive
keyword controls whether deeper levels of nested macros are also expanded. This is demonstrated in the example below:
julia> module M macro m1() 42 end macro m2() :(@m1()) end endMjulia> macroexpand(M, :(@m2()), recursive=true)42julia> macroexpand(M, :(@m2()), recursive=false):(#= REPL[16]:6 =# M.@m1)
Base.@macroexpand
—Macro@macroexpand [mod,] ex
Return equivalent expression with all macros removed (expanded). If two arguments are provided, the first is the module to evaluate in.
There are differences between@macroexpand
andmacroexpand
.
Whilemacroexpand
takes a keyword argumentrecursive
,@macroexpand
is always recursive. For a non recursive macro version, see@macroexpand1
.
Whilemacroexpand
has an explicitmodule
argument,@macroexpand
always expands with respect to the module in which it is called.
This is best seen in the following example:
julia> module M macro m() 1 end function f() (@macroexpand(@m), macroexpand(M, :(@m)), macroexpand(Main, :(@m)) ) end endMjulia> macro m() 2 end@m (macro with 1 method)julia> M.f()(1, 1, 2)
With@macroexpand
the expression expands where@macroexpand
appears in the code (moduleM
in the example). Withmacroexpand
the expression expands in the module given as the first argument.
The two-argument form requires at least Julia 1.11.
Base.@macroexpand1
—Macro@macroexpand1 [mod,] ex
Non recursive version of@macroexpand
.
Base.code_lowered
—Functioncode_lowered(f, types; generated=true, debuginfo=:default)
Return an array of the lowered forms (IR) for the methods matching the given generic function and type signature.
Ifgenerated
isfalse
, the returnedCodeInfo
instances will correspond to fallback implementations. An error is thrown if no fallback implementation exists. Ifgenerated
istrue
, theseCodeInfo
instances will correspond to the method bodies yielded by expanding the generators.
The keyworddebuginfo
controls the amount of code metadata present in the output.
Note that an error will be thrown iftypes
are not leaf types whengenerated
istrue
and any of the corresponding methods are an@generated
method.
Base.code_typed
—Functioncode_typed(f, types; kw...)
Returns an array of type-inferred lowered form (IR) for the methods matching the given generic function and type signature.
Keyword Arguments
optimize::Bool = true
: optional, controls whether additional optimizations, such as inlining, are also applied.debuginfo::Symbol = :default
: optional, controls the amount of code metadata present in the output, possible options are:source
or:none
.Internal Keyword Arguments
This section should be considered internal, and is only for who understands Julia compiler internals.
world::UInt = Base.get_world_counter()
: optional, controls the world age to use when looking up methods, use current world age if not specified.interp::Core.Compiler.AbstractInterpreter = Core.Compiler.NativeInterpreter(world)
: optional, controls the abstract interpreter to use, use the native interpreter if not specified.Examples
One can put the argument types in a tuple to get the correspondingcode_typed
.
julia> code_typed(+, (Float64, Float64))1-element Vector{Any}: CodeInfo(1 ─ %1 = Base.add_float(x, y)::Float64└── return %1) => Float64
Base.precompile
—Functionprecompile(f, argtypes::Tuple{Vararg{Any}})
Compile the given functionf
for the argument tuple (of types)argtypes
, but do not execute it.
precompile(f, argtypes::Tuple{Vararg{Any}}, m::Method)
Precompile a specific method for the given argument types. This may be used to precompile a different method than the one that would ordinarily be chosen by dispatch, thus mimickinginvoke
.
Base.jit_total_bytes
—FunctionBase.jit_total_bytes()
Return the total amount (in bytes) allocated by the just-in-time compiler for e.g. native code and data.
Base.Meta.quot
—FunctionMeta.quot(ex)::Expr
Quote expressionex
to produce an expression with headquote
. This can for instance be used to represent objects of typeExpr
in the AST. See also the manual section aboutQuoteNode.
Examples
julia> eval(Meta.quot(:x)):xjulia> dump(Meta.quot(:x))Expr head: Symbol quote args: Array{Any}((1,)) 1: Symbol xjulia> eval(Meta.quot(:(1+2))):(1 + 2)
Base.isexpr
—FunctionMeta.isexpr(ex, head[, n])::Bool
Returntrue
ifex
is anExpr
with the given typehead
and optionally that the argument list is of lengthn
.head
may be aSymbol
or collection ofSymbol
s. For example, to check that a macro was passed a function call expression, you might useisexpr(ex, :call)
.
Examples
julia> ex = :(f(x)):(f(x))julia> Meta.isexpr(ex, :block)falsejulia> Meta.isexpr(ex, :call)truejulia> Meta.isexpr(ex, [:block, :call]) # multiple possible headstruejulia> Meta.isexpr(ex, :call, 1)falsejulia> Meta.isexpr(ex, :call, 2)true
Base.isidentifier
—Function isidentifier(s) -> Bool
Return whether the symbol or strings
contains characters that are parsed as a valid ordinary identifier (not a binary/unary operator) in Julia code; see alsoBase.isoperator
.
Internally Julia allows any sequence of characters in aSymbol
(except\0
s), and macros automatically use variable names containing#
in order to avoid naming collision with the surrounding code. In order for the parser to recognize a variable, it uses a limited set of characters (greatly extended by Unicode).isidentifier()
makes it possible to query the parser directly whether a symbol contains valid characters.
Examples
julia> Meta.isidentifier(:x), Meta.isidentifier("1x")(true, false)
Base.isoperator
—Functionisoperator(s::Symbol)
Returntrue
if the symbol can be used as an operator,false
otherwise.
Examples
julia> Meta.isoperator(:+), Meta.isoperator(:f)(true, false)
Base.isunaryoperator
—Functionisunaryoperator(s::Symbol)
Returntrue
if the symbol can be used as a unary (prefix) operator,false
otherwise.
Examples
julia> Meta.isunaryoperator(:-), Meta.isunaryoperator(:√), Meta.isunaryoperator(:f)(true, true, false)
Base.isbinaryoperator
—Functionisbinaryoperator(s::Symbol)
Returntrue
if the symbol can be used as a binary (infix) operator,false
otherwise.
Examples
julia> Meta.isbinaryoperator(:-), Meta.isbinaryoperator(:√), Meta.isbinaryoperator(:f)(true, false, false)
Base.Meta.show_sexpr
—FunctionMeta.show_sexpr([io::IO,], ex)
Show expressionex
as a lisp style S-expression.
Examples
julia> Meta.show_sexpr(:(f(x, g(y,z))))(:call, :f, :x, (:call, :g, :y, :z))
Settings
This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.