Main facilities
Introduction
The Julia Base module contains a number of functions and macros suitable for performing scientific and numerical calculations, but it is not inferior to many general-purpose programming languages. Additional functionality can be found in the expanding collection. https://julialang.org/packages /[available packages]. The functions are grouped by topic below.
Some general notes.
-
To apply the module’s functions, use
import Module
to import the module andModule.fn(x)
to use the functions. -
Alternatively,
using Module' imports all exported `Module
functions into the current namespace. -
By convention, function names ending with an exclamation mark (
!
) change their arguments. Some functions have both mutable (for example,sort!
), and immutable (sort
) versions.
The behavior of the Base
and standard libraries is stable, as defined in https://semver.org /[SemVer], only if it is documented, i.e. included in https://docs.julialang.org /[Julia documentation] and is not marked as unstable. For more information, see the page API questions and answers.
General information
#
Base.exit
— Function
exit(code=0)
Stops the program and returns the exit code. The default exit code is zero. This means that the program has completed successfully. During an interactive session, the exit()
function can be called using the keyboard shortcut `^D'.
#
Base.atexit
— Function
atexit(f)
Registers the function f()
with no arguments or with one argument, called when exiting the process. The 'atexit()` interceptors are called in the LIFO order (last received — first serviced) and are executed before the object finalizers.
If f
has a method defined for a single integer argument, it will be called as f(n::Int32)
, where n
is the current exit code, otherwise it will be called as `f()'.
Compatibility: Julia 1.9
A single-argument form requires Julia 1.9. |
Exit interceptors can call exit(n)
. In this case, Julia terminates execution with exit code n
(instead of the original exit code). If the exit(n)
function is called by multiple exit interceptors, Julia terminates execution with the exit code corresponding to the last exit interceptor that called exit(n)
. (Since exit interceptors are called in LIFO order, the last caller will be the first registered interceptor.)
Note. After calling all exit interceptors, no exit interceptors can be registered anymore, and any call to atexit(f)
after all interceptors are completed will result in an exception. This situation may occur when interceptors are registered for exiting background tasks that may still be running in parallel during shutdown.
#
Base.isinteractive
— Function
isinteractive() -> Bool
Determines whether the Julia interactive session is running.
#
Base.summarysize
— Function
Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int
Calculates the amount of memory in bytes occupied by all the unique objects that are available from the argument.
Named arguments
-
`exclude': types of objects that are excluded from the crawl.
-
chargeall
: types of objects for which the size of all fields is always taken into account, even if they are usually excluded.
See also the description sizeof
.
Examples
julia> Base.summarysize(1.0)
8
julia> Base.summarysize(Ref(rand(100)))
848
julia> sizeof(Ref(rand(100)))
8
#
Base.__precompile__
— Function
__precompile__(isprecompilable::Bool)
Determines whether the file calling this function can be precompiled. The default value is true'. If precompiling a module or file is not safe, call `__precompile__(false)
so that an error occurs when trying to precompile in Julia.
#
Base.include
— Function
Base.include([mapexpr::Function,] m::Module, path::AbstractString)
Calculates the contents of the input source code file in the global scope of the module m'. For each module (except those declared with the keyword `baremodule
) has its own definition of the include
function without the m
argument, which calculates the contents of the file in this module. Returns the result of the last evaluated expression in the input file. During activation, the path to the directory containing the file is set as the local activation path for the task. With nested calls to the include
function, the search is performed relative to this path. This feature is usually used to download source code interactively or to combine files in packages that are split into multiple source code files.
Using the optional first argument mapexpr
, you can convert the included code before calculating it: for each analyzed expression expr
in path
, the include
function actually calculates mapexpr(expr)
. If the mapexpr
argument is not specified, it defaults to identity
.
Compatibility: Julia 1.5
The Julia 1.5 version is required to pass the |
#
include
— Function
include([mapexpr::Function,] path::AbstractString)
Calculates the contents of the input source code file in the global area of the containing module. Each module (except those declared with the keyword baremodule') has its own definition of the `include
function, which calculates the contents of the file in this module. Returns the result of the last evaluated expression in the input file. During activation, the path to the directory containing the file is set as the local activation path for the task. With nested calls to the include
function, the search is performed relative to this path. This feature is usually used to download source code interactively or to combine files in packages that are split into multiple source code files. The path
argument is normalized using the function normpath
, which resolves relative path characters such as ..
and converts /
to the appropriate path separator.
Using the optional first argument mapexpr
, you can convert the included code before calculating it: for each analyzed expression expr
in path
, the include
function actually calculates mapexpr(expr)
. If the mapexpr
argument is not specified, it defaults to identity
.
To calculate the contents of a file in another module, use Base.include
.
Compatibility: Julia 1.5
The Julia 1.5 version is required to pass the |
#
Base.include_string
— Function
include_string([mapexpr::Function,] m::Module, code::AbstractString, filename::AbstractString="string")
It acts in the same way as include
, but reads the code from the specified string, not from the file.
Using the optional first argument mapexpr
, you can convert the included code before calculating it: for each analyzed expression expr
in code
, the function include_string
actually calculates mapexpr(expr)
. If the mapexpr
argument is not specified, it defaults to identity
.
Compatibility: Julia 1.5
The Julia 1.5 version is required to pass the |
#
Base.include_dependency
— Function
include_dependency(path::AbstractString; track_content::Bool=true)
Declares in the module that the file, directory, or symbolic link specified in the path
argument (as a relative or absolute path) is a dependency for pre-compilation. This means that with track_content=true
, the module will need to be recompiled if the contents of path
change (if path
is a directory, the contents will be join(readdir(path))
). With track_content=false
, recompilation is triggered if the modification time mtime
for path
changes.
It is only required if the module depends on a path that is not used by include
. It is valid only during compilation.
Compatibility: Julia 1.11
To use the named |
#
__init__
— Keyword
__init__
The function __init__()
in the module is executed immediately after the module is loaded for the first time during execution. It is called once, after executing all other statements in the module. Since it is called after the module is fully imported, the functions of the __init__
submodules will be executed first. Two typical uses of the __init__
function are calling the runtime initialization functions of external C libraries and initializing global constants, which use pointers returned by external libraries. For more information, see the module section of the manual.
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}, ())
nothing
end
#
Base.which
— Method
which(f, types)
Returns the method of the f
argument (the Method
object), which will be called for arguments of the types
types.
If types
is an abstract type, the method that will be called by the invoke
function is returned.
See also the description parentmodule
, @which
and @edit
.
#
Base.methods
— Function
methods(f, [types], [module])
Returns the method table for f
.
If the types
argument is specified, it returns an array of methods of the corresponding types. If the module
argument is specified, it returns an array of methods defined in this module. You can also specify a list of modules as an array.
Compatibility: Julia 1.4
To specify the module, a Julia version of at least 1.4 is required. |
See also the description which
, @which
and methodswith
.
#
Base.MainInclude.ans
— Constant
ans
A variable referring to the last calculated value, automatically imported into the interactive command line.
#
Base.MainInclude.err
— Constant
err
A variable referring to the latest errors that occurred, automatically imported into the interactive command line. Errors that occur are collected in the exception stack.
#
Base.active_project
— Function
active_project()
Returns the path to the active Project.toml
file. See also the description Base.set_active_project
.
#
Base.set_active_project
— Function
set_active_project(projfile::Union{AbstractString,Nothing})
Sets the file specified in the projfile
as the active Project.toml
file. See also the description Base.active_project
.
Compatibility: Julia 1.8
This feature requires a Julia version of at least 1.8. |
Keywords
Below is a 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
. It is forbidden to use these keywords as variable names.
The following two-word sequences are also reserved: abstract type', `mutable struct
, primitive type'. However, you can create variables named: `abstract
, mutable
, primitive
, and `type'.
And finally: where
it is analyzed as an infix operator for writing definitions of parametric methods and types; in
and isa
are analyzed as infix operators; public
is analyzed as a keyword at the beginning of a top-level operator; outer
is analyzed as a keyword when used to change the scope of a variable in the specification of an iteration of the 'for` loop; as
is used as a keyword to rename an identifier added to the scope using import
or using'. However, it is allowed to create variables named `where
, in
, isa
, outer
and `as'.
#
module
— Keyword
module
The keyword module' declares an object `Module
— a separate global workspace of variables. Inside a module, you can make names from other modules visible (by importing) or make names from this module publicly available (by export
and `public'). Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with someone else’s. For more information, see the module section of the manual.
Examples
module Foo
import Base.show
export MyType, foo
struct MyType
x
end
bar(x) = 2x
foo(a::MyType) = bar(a.x) + 1
show(io::IO, a::MyType) = print(io, "MyType $(a.x)")
end
#
export
— Keyword
export
The export
keyword in the modules tells Julia which names should be available to the user. For example: export foo
makes the name foo' available when loading the module with the command `using
. For more information, see the module section of the manual.
#
public
— Keyword
public
The public
keyword in modules tells Julia which names should be part of the module’s public API. For example: public foo
indicates that the name foo
is public, without making it available when loading the module with the command using
. For more information, see the module section of the manual.
Compatibility: Julia 1.11
The public keyword was added in Julia 1.11. Before that, the public availability of names was less explicit. |
#
import
— Keyword
import
import Foo
loads the module or package Foo'. Names from the imported module `Foo
are accessed using dot notation (for example, Foo.foo
to access the name foo
). For more information, see the module section of the manual.
#
using
— Keyword
using
'using Foo` loads the module or package Foo' and makes its names exported using the keyword `export
, available for direct use. Names can also be referred to using dot notation (for example, Foo.foo
to access the name foo
) regardless of whether they are exported using export
. For more information, see the module section of the manual.
If two or more packages/modules export a name and this name does not refer to the same object in each package, and the packages are loaded by |
#
as
— Keyword
as
as
is used as a keyword to rename an identifier added to the scope using import
or using'. This is useful for resolving name conflicts, as well as for shortening names. (Outside of the `import
or using
as
operators It is not a keyword and can be used as a regular identifier.)
import LinearAlgebra as LA
introduces the imported standard library LinearAlgebra
into the scope as LA
.
import LinearAlgebra: eigen as eig, cholesky as chol
introduces the methods eigen
and cholesky
from LinearAlgebra
into the scope as eig
and chol
respectively.
The as
keyword works with the using
operator only when separate identifiers are entered into the scope. For example, using LinearAlgebra: eigen as eig
or using LinearAlgebra: eigen as eig, cholesky as chol
will work, but using LinearAlgebra as LA
is an invalid syntax, since renaming all names exported from LinearAlgebra
to LA
does not make sense.
#
baremodule
— Keyword
baremodule
'baremodule` declares a module that does not contain the using Base' command or local definitions
eval
and include
. Nevertheless, the Core
module is being imported. In other words,
module Mod
...
end
equivalent to
baremodule Mod
using Base
eval(x) = Core.eval(Mod, x)
include(p) = Base.include(Mod, p)
...
end
#
function
— Keyword
function
Functions are defined using the keyword function
:
function add(a, b)
return a + b
end
Abbreviated entry:
add(a, b) = a + b
The key word return
is used in exactly the same way as in other languages, but is often optional. A function without an explicit 'return` operator returns the last expression in its body.
#
macro
— Keyword
macro
The keyword macro
defines a method for inserting generated code into a program. The macro matches the sequence of expressions passed as arguments with the returned expression. The resulting expression is inserted into the program at the place where the macro is called. Macros allow you to execute generated code without calling eval
: The generated code simply becomes part of the surrounding program. Macro arguments can be expressions, literal values, and symbols. Macros can be defined with a variable number of arguments (varargs), but they do not accept named arguments. The argument __source__
containing the line number, the file name from where the macro is called, and the argument __module__
containing the module in which the macro is expanded are also implicitly passed to each macro.
For more information about writing macros, see the section of the manual on metaprogramming.
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
— Keyword
return
The 'return x` operator causes an early exit from the function and passes the value of x
to the caller. The keyword return
without a value is equivalent to return nothing' (see description `nothing
).
function compare(a, b)
a == b && return "equal to"
a < b ? "less than" : "greater than"
end
As a rule, the return
operator can be placed anywhere in the function body, including in deeply nested loops or conditional statements, but be careful with the 'do` blocks. For example:
function test1(xs)
for x in xs
iseven(x) && return 2x
end
end
function test2(xs)
map(xs) do x
iseven(x) && return 2x
x
end
end
In the first example, the return statement terminates the execution of the test1
function as soon as an even number is encountered, so calling test1([5,6,7])
returns 12
.
In the second example, one would expect the same thing, but in fact, the return
operator in this case exits the inner function (inside the do
block) and returns the value of the map
function. Therefore, calling test2([5,6,7])
returns [5,12,7]
.
When used in a top-level expression (i.e. outside a function), the return
operator causes the entire current top-level expression to terminate prematurely.
#
do
— Keyword
do
Creates an anonymous function and passes it as the first argument to the function call. For example:
map(1:10) do x
2x
end
it is equivalent to map(x->2x, 1:10)
.
You can use multiple arguments as follows.
map(1:10, 11:20) do x, y
x + y
end
#
begin
— Keyword
begin
Keywords begin...end
denote a block of code.
begin
println("Hello, ")
println("World!")
end
There is usually no need for begin
because keywords such as function
and let
, mean the beginning of the code block. See also the description ;
.
The keyword begin
can also be used for indexing. In this case, it means the first index of the collection or dimension of the array. For example, a[begin]
is the first element of the array `a'.
Compatibility: Julia 1.4
To use |
Examples
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> A[begin, :]
2-element Array{Int64,1}:
1
2
#
end
— Keyword
end
The keyword end
indicates the end of a block of expressions, for example module
, struct
, mutable struct
, begin
, let
, for
, etc.
The keyword end
can also be used for indexing. In this case, it means the last index of the collection or dimension of the array.
Examples
julia> A = [1 2; 3 4]
2×2 Array{Int64, 2}:
1 2
3 4
julia> A[end, :]
2-element Array{Int64, 1}:
3
4
#
let
— Keyword
let
The let
blocks create a strict scope and additionally introduce new local bindings.
As and other scope constructs, let
blocks define a block of code in which the represented local variables will be available. In addition, this syntax is particularly important for comma-separated assignments and variable names, which can optionally be on the same line as let
.:
let var1 = value1, var2, var3 = value3
code
end
The variables presented in this line are local to the let
block, and assignments are calculated in order, with each right-hand side calculated within the scope without taking into account the name on the left. For this reason, the expression let x = x
will make sense, since the x
in the left and right parts are different variables, and the left part locally obscures the x
from the outer area. This can even be useful, since new local variables are created anew each time they enter local areas, but this only manifests itself if the variables continue to exist outside their area due to closures. The expression let
without assignment, such as var2
in the example above, declares a new local variable that is not yet bound to a value.
In contrast, the blocks 'begin` also groups several expressions together, but does not introduce scope and does not have a special assignment syntax.
Examples
In the function below, there is a single x
that is iteratively updated three times using map
. All returned closures refer to this x
in its final value.:
julia> function test_outer_x()
x = 0
map(1:3) do _
x += 1
return ()->x
end
end
test_outer_x (generic function with 1 method)
julia> [f() for f in test_outer_x()]
3-element Vector{Int64}:
3
3
3
However, if we add a let
block that introduces a new local variable, we will end up with three different variables (one in each iteration), even if we decide to use (shade) the same name.
julia> function test_let_x()
x = 0
map(1:3) do _
x += 1
let x = x
return ()->x
end
end
end
test_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 in a similar way when run multiple times. A distinctive feature of let
is its ability to concisely declare new local variables (local
) that can obscure external variables in different ways. For example, direct use of the function argument do
similarly records three different variables.:
julia> function test_do_x()
map(1:3) do x
return ()->x
end
end
test_do_x (generic function with 1 method)
julia> [f() for f in test_do_x()]
3-element Vector{Int64}:
1
2
3
#
if
— Keyword
if/elseif/else
The if
/elseif
/else
construction allows you to perform conditional calculations: parts of the code are calculated or not calculated depending on the value of the boolean expression. The syntax of the conditional construction if
/elseif
/else
is arranged as follows.
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 expression x < y
is true, then the corresponding block is evaluated; otherwise, the condition expression x > y
is evaluated, and if it is true, the corresponding block is evaluated. If none of the expressions is true, the 'else` block is evaluated. The elseif
and else
blocks are optional. There can be any number of elseif
blocks.
Unlike in some other languages, conditions must be of type Bool'. The ability to convert a condition to a `Bool
is not enough.
julia> if 1 end
ERROR: TypeError: non-boolean (Int64) used in boolean context
#
for
— Keyword
for
The 'for` loop allows you to recalculate a block of statements with iteration over a sequence of values.
An iteration variable is always a new variable, even if a variable with that name already exists in the external scope. Use outer
to reapply an existing local variable for iteration.
Examples
julia> for i in [1, 4, 0]
println(i)
end
1
4
0
#
while
— Keyword
while
The 'while` loop allows you to re-evaluate the conditional expression and continue to evaluate the body of the while loop until the expression is true. If the condition expression is false at the first evaluation, the loop body is never evaluated.
Examples
julia> i = 1
1
julia> while i < 5
println(i)
global i += 1
end
1
2
3
4
#
break
— Keyword
break
Performs an immediate exit from the cycle.
Examples
julia> i = 0
0
julia> while true
global i += 1
i > 5 && break
println(i)
end
1
2
3
4
5
#
continue
— Keyword
continue
Skips the rest of the current iteration of the loop.
Examples
julia> for i = 1:6
iseven(i) && continue
println(i)
end
1
3
5
#
try
— Keyword
try/catch
The try
/catch
operator allows you to intercept errors (exceptions) caused by the function throw
so that the program execution can continue. For example, in the following code, an attempt is made to write to a file, but the user receives a warning and execution continues if writing to the file is not possible.:
try
open("/danger", "w") do f
println(f, "Hello")
end
catch
@warn "Could not write file."
end
or if the file cannot be read into a variable:
lines = try
open("/danger", "r") do f
readlines(f)
end
catch
@warn "File not found."
end
Using the catch e
syntax (where e
is any variable), the exception object is assigned to the specified variable in the catch
block.
The 'try`/catch
construction is useful because it allows you to immediately transfer a deeply nested calculation to a much higher level in the stack of calling functions.
#
finally
— Keyword
finally
Executes a specific code when exiting a given block of code, regardless of how the exit occurs. For example, this way you can ensure that an open file is closed.:
f = open("file")
try
operate_on_file(f)
finally
close(f)
end
When control is transferred from the block try
(for example, due to the execution of the operator return
or due to normal termination), the function is executed close(f)
. If the exit from the try
block occurs due to an exception, this exception will be passed on. The 'catch` block can also be used in combination with try
and finally'. In this case, the `finally
block will be executed after the catch
block handles the error.
#
quote
— Keyword
quote
The quote
keyword creates several expression objects based on a block of code without explicitly using the constructor. Expr
. For example:
ex = quote
x = 1
y = 2
x + y
end
Unlike the other way of quoting, :( ... )
, this method adds QuoteNode
elements to the expression tree, which must be processed during operations with the tree. In all other cases, the :( ... )
and quote' blocks .. end
are equivalent.
#
local
— Keyword
local
The keyword local
declares a new local variable. For more information, see the section of the manual devoted to variable scopes.
Examples
julia> function foo(n)
x = 0
for i = 1:n
local x # объявить локальную для цикла переменную x
x = i
end
x
end
foo (generic function with 1 method)
julia> foo(10)
0
#
global
— Keyword
global
When using the expression global x
, the variable x
in the current scope and its internal scopes starts referring to a global variable with the same name. For more information, see the section of the manual devoted to variable scopes.
Examples
julia> z = 3
3
julia> function foo()
global z = 6 # использовать переменную z, определенную вне foo
end
foo (generic function with 1 method)
julia> foo()
6
julia> z
6
#
outer
— Keyword
for outer
Reuses an existing local variable for iteration in the 'for` loop.
For more information, see the section of the manual devoted to variable scopes.
See also the description for
.
Examples
julia> function f()
i = 0
for i = 1:3
# пусто
end
return i
end;
julia> f()
0
julia> function f()
i = 0
for outer i = 1:3
# пусто
end
return i
end;
julia> f()
3
julia> i = 0 # глобальная переменная
for outer i = 1:3
end
ERROR: syntax: no outer local variable declaration exists for "for outer"
[...]
#
const
— Keyword
const
The keyword const
is used to declare global variables whose values will not change. Almost always (and especially in performance-demanding code), global variables should be declared as constants in this way.
const x = 5
Multiple variables can be declared in a single const
expression.:
const y, z = 7, 11
Note that const
applies to only one operation =
, so the expression const x = y = 1
declares only the variable x
as a constant, but not y
. In turn, the expression const x = const y = 1
declares both x
and y
as constants.
Note that "constancy" does not apply to mutable containers; only the relationship between a variable and its value is immutable. For example, if 'x` is an array or dictionary, its elements can still be modified, added, or deleted.
In some cases, when changing the value of a variable declared as const
, a warning is issued, not an error. However, this can make the program unpredictable or damage its state, so this should be avoided. This function is intended solely for convenience when working interactively.
#
struct
— Keyword
struct
The most widely used type in Julia is structure. Its definition consists of a name and a set of fields.
struct Point
x
y
end
Fields can have type constraints that can be parameterized.:
struct Point{X}
x::X
y::Float64
end
An abstract supertype can also be declared in the structure using the syntax <:
:
struct Point <: AbstractPoint
x
y
end
By default, struct
instances are immutable: they cannot be changed after creation. However, using the keyword mutable struct
you can declare a type whose instances can be modified.
In the section of the manual dedicated to composite types, additional information is provided, for example, about the definition of constructors.
#
mutable struct
— Keyword
mutable struct
The keyword mutable struct
acts in the same way as struct
, but additionally allows you to specify fields of the type after creating its instance.
Individual fields of a mutable structure can be made immutable by marking them as const
:
mutable struct Baz
a::Int
const b::Float64
end
Compatibility: Julia 1.8
To apply the |
For more information, see the section of the manual on composite types.
#
Base.@kwdef
— Macro
@kwdef typedef
This is an auxiliary macro that automatically determines the constructor based on the keyword for the type declared in the expression typedef', which should be the expression `struct
or mutable struct'. The default argument is specified when declaring fields like `field::T = default
or `field = default'. If no default value is specified, the named argument becomes a mandatory named argument in the constructor of the resulting type.
Internal constructors can still be defined, but at least one of them must accept arguments in the same form as the default internal constructor (i.e., one positional argument per field) in order to work correctly with the external keyword constructor.
Compatibility: Julia 1.1
For the |
Compatibility: Julia 1.9
This macro has been exported since version Julia 1.9. |
Examples
julia> @kwdef struct Foo
a::Int = 1 # указанное значение по умолчанию
b::String # требуемое ключевое слово
end
Foo
julia> Foo(b="hi")
Foo(1, "hi")
julia> Foo()
ERROR: UndefKeywordError: keyword argument `b` not assigned
Stacktrace:
[...]
#
abstract type
— Keyword
abstract type
The abstract type
declares a type that does not allow instantiation, but simply serves as a node in the type graph, describing sets of related concrete types — types that are descendants of this abstract type. Abstract types form a conceptual hierarchy that makes the Julia type system more than just a collection of object implementations. For example:
abstract type Number end
abstract type Real <: Number end
#
primitive type
— Keyword
primitive type
The primitive type
declares a specific type whose data consists only of a sequence of bits. Classical examples of primitive types are integers and floating-point values. Here are some examples of embedded primitive type declarations.
primitive type Char 32 end
primitive type Bool <: Integer 8 end
The number after the name indicates how many bits are required to store the type. Currently, only sizes that are multiples of 8 bits are supported. Advertisement Bool
demonstrates how a primitive type can be declared as a subtype of a supertype.
#
where
— Keyword
where
The keyword where
creates a type unionAll
, which can be represented as an iterable union of other types for all values of a certain variable. For example, the type Vector{T} where T<:Real
includes all vectors (Vector
), whose elements are real numbers (Real
).
If no bounding variable is specified, it defaults to Any
:
Vector{T} where T # краткая форма для `where T<:Any`
Variables can also have lower bounds.:
Vector{T} where T>:Int
Vector{T} where Int<:T<:Real
There is also an abbreviated syntax for nested where
expressions. For example, this code:
Pair{T, S} where S<:Array{T} where T<:Number
it can be shortened as follows:
Pair{T, S} where {T<:Number, S<:Array{T}}
This form is often found in method signatures.
Note that when using this form of notation, variables are listed starting from the outermost one. This corresponds to the order in which variables are substituted when applying a type to parameter values using the syntax T{p1, p2, ...}
.
#
...
— Keyword
...
The expansion operator (splat operator, ...
) represents a sequence of arguments. The ' operator...
can be used in function definitions to indicate that a function accepts an arbitrary number of arguments. Using the ' operator...
you can also apply the 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)
15
julia> add([1, 2, 3]...)
6
julia> add(7, 1:100..., 1000:1100...)
111107
#
;
— Keyword
;
The ';` character performs the same role in Julia as in many C-like languages, indicating the end of the previous statement.
The ;
character does not have to be at the end of a line: it can be used to separate operators in a single line or to combine operators into a single expression.
If you add a ;
to the end of a line in the REPL, the result of this expression is not output.
In function declarations, the ;
character separates regular arguments from named arguments. For the same purpose, it can be used in function calls.
In array literals, the contents of arguments separated by semicolons are combined. If the separator is a single character ;
, the contents are combined vertically (that is, along the first dimension), in the case of the separator ;;
the contents are combined horizontally (in the second dimension), in the case of the separator ;;;
unification takes place in the third dimension, etc. Such a separator can also be used in the last position in square brackets to add the final dimensions of length 1.
The character ;
in the first position in parentheses can be used to construct a named tuple. The same syntax (; ...)
on the left side of the assignment allows you to destructure properties.
If you enter the character ;
in an empty line in the standard REPL environment, it switches to shell mode.
Examples
julia> function foo()
x = "Hello, "; x *= "World!"
return x
end
foo (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")
###
end
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> [1; 3;; 2; 4;;; 10*A]
2×2×2 Array{Int64, 3}:
[:, :, 1] =
1 2
3 4
[:, :, 2] =
10 20
30 40
julia> [2; 3;;;]
2×1×1 Array{Int64, 3}:
[:, :, 1] =
2
3
julia> nt = (; x=1) # без символа «;» или запятой в конце происходило бы присваивание переменной 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; # задаем переменные b и x путем деструктуризации свойств
julia> b, x
(2, 1)
julia> ; # при вводе «;» приглашение к вводу меняется на shell>
shell> echo hello
hello
#
=
— Keyword
=
'=` is an assignment operator.
-
If
a
is a variable andb
is an expression, as a result of the assignmenta = b
, the variablea
will refer to the valueb
. -
For the function
f(x)
, the assignmentf(x) = x
defines a new constant functionf
or, if the functionf
is already defined, adds a new method tof
. This use case is equivalent to the syntax `function f(x); x; end'. -
a[i] = v
causes xref:./collections.adoc#Base.setindex!(a,v,i)
. -
a.b = c
causes xref:./base.adoc#Base.setproperty!(a,:b,c)
. -
Inside the function call
f(a=b)`passes `b
as the value of the named argument `a'. -
Inside parentheses with commas
(a=1,)
creates an instance of the typeNamedTuple
.
Examples
When assigning object b
to variable a
, no copy of b
is created; to do this, use the function copy
or deepcopy
.
julia> b = [1]; a = b; b[1] = 2; a
1-element Array{Int64, 1}:
2
julia> b = [1]; a = copy(b); b[1] = 2; a
1-element Array{Int64, 1}:
1
Collections passed to functions are also not copied. Functions can change the contents of objects referenced by their arguments. (It is customary to add the suffix "!" to the names of such functions.)
julia> function f!(x); x[:] .+= 1; end
f! (generic function with 1 method)
julia> a = [1]; f!(a); a
1-element Array{Int64, 1}:
2
The values of an iterable object can be assigned to several variables in parallel.:
julia> a, b = 4, 5
(4, 5)
julia> a, b = 1:3
1:3
julia> a, b
(1, 2)
You can assign values sequentially to several variables. This returns the value of the rightmost expression.:
julia> a = [1]; b = [2]; c = [3]; a = b = c
1-element Array{Int64, 1}:
3
julia> b[1] = 2; a, b, c
([2], [2], [2])
When assigned by an index that goes beyond the bounds, items are not added to the collection. If the collection has a type Vector
, you can add elements to it using the function push!
or append!
.
julia> a = [1, 1]; a[3] = 2
ERROR: 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
When assigning []
, items from the collection are not deleted; instead, use the function filter!
.
julia> a = collect(1:3); a[a .<= 1] = []
ERROR: DimensionMismatch: tried to assign 0 elements to 1 destinations
[...]
julia> filter!(x -> x > 1, a) # операция производится на месте и поэтому эффективнее, чем a = a[a .> 1]
2-element Array{Int64, 1}:
2
3
#
?:
— Keyword
a ? b : c
The short form of writing conditional operators; means "if a
, calculate b
, otherwise calculate `c`". Also called the ternary operator.
This syntax is equivalent to if a; b else c end
, but is often used to emphasize the choice between b
and c
within a more complex expression, rather than the consequences of calculating b
or `c'.
For more information, see the section of the manual on order of execution.
Examples
julia> x = 1; y = 2;
julia> x > y ? println("x is larger") : println("x is not larger")
x is not larger
julia> x > y ? "x is larger" : x == y ? "x and y are equal" : "y is larger"
"y is larger"
Standard modules
#
Main
— Module
Main
Main
is a top-level module. Initially, in Julia, the Main
module is the current one. Variables defined on the command line are added to the Main
module, and the varinfo
function returns variables from the `Main' module.
julia> @__MODULE__
Main
#
Core
— Module
Core
The Core
module contains all identifiers that are considered embedded in the language, meaning they are part of the language itself, not libraries. The using Core
command is implicitly applied in each module, since no operations are possible without these definitions.
#
Base
— Module
Base
Julia’s basic library. The Base
module contains the main functions (the contents of base/'). All modules implicitly use the `using Base
command, as these functions are necessary in the vast majority of cases.
Base Submodules
#
Base.Docs
— Module
Docs
The Docs
module provides a macro @doc
, which can be used to set and receive documentation metadata for Julia objects.
For more information, see the section of the manual on documentation .
#
Base.Iterators
— Module
Methods for working with iterators.
#
Base.Libc
— Module
An interface for libc, the C standard library.
#
Base.Meta
— Module
Auxiliary functions for metaprogramming.
#
Base.StackTraces
— Module
Tools for collecting stack traces and working with them. They are mainly used to fix build errors.
#
Base.Sys
— Module
Provides methods for obtaining information about the hardware and operating system.
#
Base.Threads
— Module
Multithreading support.
All objects
#
Core.:===
— Function
===(x,y) -> Bool
≡(x,y) -> Bool
Determines whether x
and y
are identical, i.e. indistinguishable for any program. First, the types x
and y
are compared. If they are the same, mutable objects are compared by address in memory, while immutable objects (such as numbers) are compared by content at the bit level. Sometimes this function is called egal. It always returns a value of type `Bool'.
Examples
julia> a = [1, 2]; b = [1, 2];
julia> a == b
true
julia> a === b
false
julia> a === a
true
#
Core.isa
— Function
isa(x, type) -> Bool
Determines whether x
belongs to the type `type'. It can also be used as an infix operator, for example, `x isa type'.
Examples
julia> isa(1, Int)
true
julia> isa(1, Matrix)
false
julia> isa(1, Char)
false
julia> isa(1, Number)
true
julia> 1 isa Number
true
#
Base.isequal
— Function
isequal(x, y) -> Bool
Similarly ==
, except for handling floating-point numbers and missing values. The isequal
function treats all floating-point values of NaN
as equal to each other, the value of -0.0
as unequal to 0.0
, and the value of missing
— as equal to missing'. It always returns a value of type `Bool
.
'isequal` is an equivalence relation: it is reflexive (===
implies isequal
), symmetric (isequal(a, b)
implies isequal(b, a)
) and transitive (isequal(a, b)
and isequal(b, c)
implies isequal(a, c)
).
Implementation
The default implementation of the isequal' function calls `==
, so for a type that is not related to floating-point values, it is usually sufficient to use ==
.
'isequal' is a comparison function used by hash tables (Dict
). hash(x) == hash(y)
should follow from `isequal(x,y)'.
This usually means that types for which there is a custom method ==
or isequal
must implement the corresponding method. hash
(and vice versa). The implementation of isequal' for collections usually calls `isequal
recursively for all contents.
In addition, the 'isequal` function is related to 'isless`, and together they define a fixed general order: only one of the expressions isequal(x, y)
, isless(x, y)
or isless(y, x)
must be true' (and the other two must be `false
).
Scalar types usually do not require the implementation of isequal
separately from ==
, unless they represent floating-point numbers for which a more efficient implementation is possible than the universal method (based on isnan
, signbit
and ==
).
Examples
julia> isequal([1., NaN], [1., NaN])
true
julia> [1., NaN] == [1., NaN]
false
julia> 0.0 == -0.0
true
julia> isequal(0.0, -0.0)
false
julia> missing == missing
missing
julia> isequal(missing, missing)
true
isequal(x)
Creates a function whose argument is compared to x
via 'isequal`, i.e. a function equivalent to y -> isequal(y, x)
.
The returned function is of type Base.Fix2{typeof(isequal)}
and can be used to implement specialized methods.
#
Base.isless
— Function
isless(x, y)
Checks whether x
is smaller than y
, according to a fixed general order (determined in combination with the function isequal
). The isless
function is not defined for all pairs of types `(x, y)'. However, if it is defined, the following conditions must be met.
-
If
isless(x, y)
is defined, thenisless(y, x)
andisequal(x, y)
should also be defined, and only one of these three expressions should return the valuetrue
. -
The relation defined by the function
isless
is transitive, that is, fromisless(x, y) && isless(y,z)
followsisless(x, z)
.
Values that are usually unordered, such as NaN', follow the normal values. In the order of the values `missing
is at the very end.
This is the default comparison used by the function sort!
.
Implementation
This function should be implemented for non-numeric types that have a common order. For numeric types, it must be implemented only if the type provides special values, for example, NaN'. Types with partial order must implement
<`. In the documentation for alternative orders you can learn how to define alternative ordering methods that are used in sorting and similar functions.
Examples
julia> isless(1, 3)
true
julia> isless("Red", "Blue")
false
#
Base.isunordered
— Function
isunordered(x)
Returns true
if the value of x
is not ordered by <
, for example, NaN
or `missing'.
The values for which this predicate returns true' can be ordered in other ways, for example, by `isless
.
Compatibility: Julia 1.7
This feature requires a version of Julia at least 1.7. |
#
Base.ifelse
— Function
ifelse(condition::Bool, x, y)
Returns x
if condition
is true', otherwise it returns `y
. Is it different from ?`or `if
because it is a regular function, so all arguments are evaluated first. In some cases, using ifelse
instead of the if
operator allows you to eliminate branching in the generated code and ensure higher performance of continuous loops.
Examples
julia> ifelse(1 > 2, 1, 2)
2
#
Core.typeassert
— Function
typeassert(x, type)
Causes an error TypeError
, if the condition x isa type
is not met. This function is called when using the syntax `x::type'.
Examples
julia> typeassert(2.5, Int)
ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64
Stacktrace:
[...]
#
Core.tuple
— Function
tuple(xs...)
Creates a tuple of the specified objects.
See also the description Tuple
, ntuple
and NamedTuple
.
Examples
julia> tuple(1, 'b', pi)
(1, 'b', π)
julia> ans === (1, 'b', π)
true
julia> Tuple(Real[1, 2, pi]) # принимает коллекцию
(1, 2, π)
#
Base.ntuple
— Function
ntuple(f, n::Integer)
Creates a tuple of length n
, each element of which is calculated using the function f(i)
, where i
is the index of the element.
Examples
julia> ntuple(i -> 2*i, 4)
(2, 4, 6, 8)
ntuple(f, ::Val{N})
Creates a tuple of length N
, each element of which is calculated using the function f(i)
, where i
is the index of the element. Thanks to the Val(N)
argument, the code created using this variant of the ntuple function can be more efficient than when specifying the length as an integer. But the option ntuple(f, N)
is preferable to ntuple(f, Val(N))
in cases where N
cannot be determined at compile time.
Examples
julia> ntuple(i -> 2*i, Val(4))
(2, 4, 6, 8)
#
Base.hash
— Function
hash(x[, h::UInt]) -> UInt
Calculates an integer hash code such that isequal(x,y)
implies hash(x)==hash(y)'. The optional second argument `h
is the hash code mixed with the result.
For new types, a form with two arguments should be implemented. To do this, the hash
function with two arguments is usually called recursively in order to mix the content hashes with each other (and with h
). As a rule, any type for which the hash function is implemented must also have its own implementation. ==
(and therefore isequal
) so that the above condition is met.
The hash value may change when starting a new Julia process.
julia> a = hash(10)
0x95ea2955abd45275
julia> hash(10, a) # использовать в качестве второго аргумента только выходные данные другой хэш-функции
0xd42bad54a8575b16
#
Base.finalizer
— Function
finalizer(f, x)
Registers the function f(x)
, which should be called if there are no references to x
available to the program, and returns x'. 'x
must be of type mutable struct
, otherwise this function will return an error.
The 'f` function should not cause task switching, which means that most I/O operations such as println' are eliminated. For debugging purposes, it may be useful to use the macro `@async
(to delay context switching until finalizer execution is complete) or the keyword ccall
to call C I/O functions directly.
Please note that the "age of the world" is not guaranteed to be available to perform the "f" function. It can be called at the "age of the world" in which the finalizer was registered, or at any later "age of the world".
Examples
finalizer(my_mutable_struct) do x
@async println("Finalizing $x.")
end
finalizer(my_mutable_struct) do x
ccall(:jl_safe_printf, Cvoid, (Cstring, Cstring), "Finalizing %s.", repr(x))
end
The finalizer can be registered when creating an object. Note that the following example implicitly assumes that the finalizer returns the created mutable structure `x'.
mutable struct MyMutableStruct
bar
function MyMutableStruct(bar)
x = new(bar)
f(t) = @async println("Finalizing $t.")
finalizer(f, x)
end
end
#
Base.finalize
— Function
finalize(x)
Immediately executes the finalizers registered for object `x'.
#
Base.deepcopy
— Function
deepcopy(x)
Creates a deep copy of `x': the entire contents are recursively copied, so that a completely independent object is obtained. For example, when copying an array deeply, deep copies of all the objects contained in it are created and a new array with a consistent relationship structure is obtained (for example, if the first two elements in the original array are the same object, the first two elements of the new array will also be a deep copy of this object). Calling the `deepcopy' function for an object is usually equivalent to serializing it and then deserializing it.
Although this is usually not required, in user-defined types, you can override the default behavior of the deepcopy
function. For this, a specialized version of the deepcopy_internal(x::T, dict' function is defined.::IdDict)
(which is not used for other purposes). Here, 'T` is the type for which the function is being redefined, and dict
tracks objects that are copied recursively. In the definition, deepcopy_internal
should be used instead of deepcopy
, and the dict
variable should be updated accordingly before returning.
#
Base.getproperty
— Function
getproperty(value, name::Symbol)
getproperty(value, name::Symbol, order::Symbol)
The syntax is a.b
calls getproperty(a, :b)'. Using the syntax `@atomic order a.b
, the call getproperty(a, :b, :order)
is made, and using the syntax @atomic a.b', the call `getproperty(a, :b, :sequentially_consistent)
is made.
Examples
julia> struct MyType{T <: Number}
x::T
end
julia> function Base.getproperty(obj::MyType, sym::Symbol)
if sym === :special
return obj.x + 1
else # использовать getfield
return getfield(obj, sym)
end
end
julia> obj = MyType(1);
julia> obj.special
2
julia> obj.x
1
Overload getproperty
only if necessary, as this can lead to confusion if the syntax behavior is obj.f
is unusual. Also, keep in mind that using methods is often preferable. For more information, see also the style guide.: Use exported methods instead of direct access to the field.
See also the description getfield
, propertynames
and setproperty!
.
#
Base.setproperty!
— Function
setproperty!(value, name::Symbol, x)
setproperty!(value, name::Symbol, x, order::Symbol)
The syntax a.b = c
calls setproperty!(a, :b, c)'. Using the syntax `@atomic order a.b = c
, a call is made to setproperty!(a, :b, c, :order)
, and using the syntax @atomic a.b = c', a call is made to `setproperty!(a, :b, c, :sequentially_consistent)
.
Compatibility: Julia 1.8
For |
See also the description setfield!
, propertynames
and getproperty
.
#
Base.replaceproperty!
— Function
replaceproperty!(x, f::Symbol, expected, desired, success_order::Symbol=:not_atomic, fail_order::Symbol=success_order)
Executes for x.f
comparison operation with the exchange of expected
for desired
according to the rules. The syntax @atomicreplace x.f expected => desired
can be used instead of the function call form.
See also the description replacefield!
setproperty!
and setpropertyonce!
.
#
Base.swapproperty!
— Function
swapproperty!(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 both parts should have one common expression `getproperty'.
See also the description swapfield!
and setproperty!
.
#
Base.modifyproperty!
— Function
modifyproperty!(x, f::Symbol, op, v, order::Symbol=:not_atomic)
The syntax @atomic op(x.f, v)
(and its equivalent @atomic x.f op v
) returns modifyproperty!(x, :f, op, v, :sequentially_consistent)
, where the first argument must be a 'getproperty` expression and is changed atomically.
The call op(getproperty(x, f), v)
should return the default value that can be stored in the 'f` field of the x
object. In particular, as opposed to the behavior 'setproperty! by default, the `convert function is not called automatically.
See also the description modifyfield!
and setproperty!
.
#
Base.setpropertyonce!
— Function
setpropertyonce!(x, f::Symbol, value, success_order::Symbol=:not_atomic, fail_order::Symbol=success_order)
Executes for x.f
a comparison operation with an exchange, assigning the value value
if it was not previously set. The syntax @atomiconce x.f = value
can be used instead of the function call form.
See also the description setfieldonce!
, setproperty!
and replaceproperty!
.
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
#
Base.propertynames
— Function
propertynames(x, private=false)
Returns a tuple or vector of properties ('x.property`) of the object x
. It usually acts the same way as fieldnames(typeof(x))
, but types that overload the function 'getproperty`, as a rule, must also overload propertynames
to get the properties of an instance of a type.
The function propertynames(x)
can return the names of only public properties included in the documented interface of the object x'. If you also need to return the names of private properties intended for internal use, pass the value `true
for the optional second argument. When auto-completing with the TAB key in the REPL for x.
only the properties for which `private=false' are displayed.
See also the description hasproperty
, hasfield
.
#
Base.hasproperty
— Function
hasproperty(x, s::Symbol)
Returns a boolean value indicating whether s
is one of the native properties of object x
.
Compatibility: Julia 1.2
This feature requires a Julia version of at least 1.2. |
See also the description propertynames
, hasfield
.
#
Core.getfield
— Function
getfield(value, name::Symbol, [order::Symbol])
getfield(value, i::Int, [order::Symbol])
Extracts a field from a composite value
object by name or position. If necessary, you can specify the order for this operation. If the field is declared with the keyword @atomic
, it is strongly recommended that the specified order be compatible with the save operations in this location. Otherwise, if the @atomic
declaration is missing and this parameter is specified, it should be :not_atomic
. See also the description getproperty
and fieldnames
.
Examples
julia> a = 1//2
1//2
julia> getfield(a, :num)
1
julia> a.num
1
julia> getfield(a, 1)
1
#
Core.setfield!
— Function
setfield!(value, name::Symbol, x, [order::Symbol])
setfield!(value, i::Int, x, [order::Symbol])
Assigns x
to the named field of the value
object of the composite type. The 'value` object must be mutable, and x
must be a subtype of fieldtype(typeof(value), name)
. In addition, you can specify the order for this operation. If the field is declared with the keyword @atomic
, the order must be specified. Otherwise, if the @atomic
declaration is missing and this parameter is specified, it should be :not_atomic
. See also the description setproperty!
.
Examples
julia> mutable struct MyMutableStruct
field::Int
end
julia> a = MyMutableStruct(1);
julia> setfield!(a, :field, 2);
julia> getfield(a, :field)
2
julia> a = 1//2
1//2
julia> setfield!(a, :num, 3);
ERROR: setfield!: immutable struct of type Rational cannot be changed
#
Core.modifyfield!
— Function
modifyfield!(value, name::Symbol, op, x, [order::Symbol]) -> Pair
modifyfield!(value, i::Int, op, x, [order::Symbol]) -> Pair
Atomically performs operations to obtain and set a field after applying the op
function.
y = getfield(value, name) z = op(y, x) setfield!(value, name, z) return y => z
If such a feature (for example, atomic increment) is supported by the hardware, operations can be optimized using the appropriate hardware instruction. Otherwise, a loop will be used.
Compatibility: Julia 1.7
This feature requires a version of Julia at least 1.7. |
#
Core.replacefield!
— Function
replacefield!(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 performs the operations of obtaining a field and conditionally assigning the specified value to it.
y = getfield(value, name, fail_order) ok = y === expected if ok setfield!(value, name, desired, success_order) end return (; old = y, success = ok)
If this capability is supported by the hardware, operations can be optimized using the appropriate hardware instruction. Otherwise, a loop will be used.
Compatibility: Julia 1.7
This feature requires a version of Julia at least 1.7. |
#
Core.swapfield!
— Function
swapfield!(value, name::Symbol, x, [order::Symbol])
swapfield!(value, i::Int, x, [order::Symbol])
Performs simultaneous field acquisition and assignment operations atomically:
y = getfield(value, name) setfield!(value, name, x) return y
Compatibility: Julia 1.7
This feature requires a version of Julia at least 1.7. |
#
Core.setfieldonce!
— Function
setfieldonce!(value, name::Union{Int,Symbol}, desired,
[success_order::Symbol, [fail_order::Symbol=success_order]) -> success::Bool
Atomically performs the operations of assigning the specified value to the field, if it has not already been set.
ok = !isdefined(value, name, fail_order) if ok setfield!(value, name, desired, success_order) end return ok
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
#
Core.isdefined
— Function
isdefined(m::Module, s::Symbol, [order::Symbol])
isdefined(object, s::Symbol, [order::Symbol])
isdefined(object, index::Int, [order::Symbol])
Checks whether a global variable or an object field is defined. The arguments can be a module and a symbol, a composite object and a field name (in the form of a symbol) or an index. If necessary, you can specify the order for this operation. If the field is declared with the keyword @atomic
, it is strongly recommended that the specified order be compatible with the save operations in this location. Otherwise, if the @atomic
declaration is missing and this parameter is specified, it should be `:not_atomic'.
To check if an array element is defined, use the function instead isassigned
.
See also the description @isdefined
.
Examples
julia> isdefined(Base, :sum)
true
julia> isdefined(Base, :NonExistentMethod)
false
julia> a = 1//2;
julia> isdefined(a, 2)
true
julia> isdefined(a, 3)
false
julia> isdefined(a, :num)
true
julia> isdefined(a, :numerator)
false
#
Base.@isdefined
— Macro
@isdefined s -> Bool
Checks whether the variable s
is defined in the current scope.
See also the function description isdefined
, which checks the properties of fields, functions isassigned
, which checks array indexes, and functions haskey
, which checks other mappings.
Examples
julia> @isdefined newvar
false
julia> newvar = 1
1
julia> @isdefined newvar
true
julia> function f()
println(@isdefined x)
x = 3
println(@isdefined x)
end
f (generic function with 1 method)
julia> f()
false
true
#
Base.convert
— Function
convert(T, x)
Converts x
to a value of type `T'.
If T
is an integer type (Integer
), an error occurs InexactError
in the case when the value x
cannot be represented as type T
, for example, if the value x
is not an integer or exceeds the range supported by type T
.
Examples
julia> convert(Int, 3.0)
3
julia> convert(Int, 3.5)
ERROR: InexactError: Int64(3.5)
Stacktrace:
[...]
If T
is a type AbstractFloat
, returns the value closest to x
, supported by type `T'. When determining the nearest value, Inf is considered as a value one unit of least precision (ulp) greater than `floatmax(T)'.
julia> x = 1/3
0.3333333333333333
julia> convert(Float32, x)
0.33333334f0
julia> convert(BigFloat, x)
0.333333333333333314829616256247390992939472198486328125
If 'T` is a collection type and x
is a collection, the convert(T, x)
function can return an alias for the entire object x
or part of it.
julia> x = Int[1, 2, 3];
julia> y = convert(Vector{Int}, x);
julia> y === x
true
See also the description round
, trunc
, oftype
, reinterpret
.
#
Base.promote
— Function
promote(xs...)
Converts all arguments to a common type and returns them as a tuple. If none of the arguments can be converted, an error occurs.
See also the description 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)
Float32
julia> reduce(Base.promote_typejoin, (Int8, Float16, Float32))
Real
julia> promote(1, "x")
ERROR: promotion of types Int64 and String failed to change any arguments
[...]
julia> promote_type(Int, String)
Any
#
Base.oftype
— Function
oftype(x, y)
Converts y
to the object type x
, i.e. convert(typeof(x), y)
.
Examples
julia> x = 4;
julia> y = 3.;
julia> oftype(x, y)
3
julia> oftype(y, x)
4.0
#
Base.widen
— Function
widen(x)
If 'x` is a type, it returns a broader type, that is, such that the arithmetic operations +
and -
are guaranteed to be performed without overflow and loss of precision for any combination of values supported by the type x
.
For fixed-size integer types with a length of less than 128 bits, the widen
function returns a type with twice the number of bits.
If x
is a value, it is converted to widen(typeof(x))
.
Examples
julia> widen(Int32)
Int64
julia> widen(1.5f0)
1.5
#
Base.identity
— Function
identity(x)
The identity function. Returns its argument.
See also the function description one
and oneunit
and the I
operator from the library LinearAlgebra
.
Examples
julia> identity("Well, what did you expect?")
"Well, what did you expect?"
#
Core.WeakRef
— Type
WeakRef(x)
'w = WeakRef(x)` creates https://en.wikipedia.org/wiki/Weak_reference [weak reference] to Julia’s value x
: Although w
contains a reference to x
, this does not prevent the garbage collector from deleting the value of x
. w.value
has the value x
(if x
has not yet been deleted by the garbage collector) or nothing
(if x
has been deleted by the garbage collector).
julia> x = "a string"
"a string"
julia> w = WeakRef(x)
WeakRef("a string")
julia> GC.gc()
julia> w # ссылка поддерживается посредством `x`
WeakRef("a string")
julia> x = nothing # очищаем ссылку
julia> GC.gc()
julia> w
WeakRef(nothing)
Type Properties
Type relations
#
Base.supertype
— Function
supertype(T::DataType)
Returns the supertype of the data type T
.
Examples
julia> supertype(Int32)
Signed
#
Core.Type
— Type
Core.Type{T}
Core.Type
is an abstract type, of which all objects of types are instances. The only instance of the single type Core.Type{T}
— object T
.
Examples
julia> isa(Type{Float64}, Type)
true
julia> isa(Float64, Type)
true
julia> isa(Real, Type{Float64})
false
julia> isa(Real, Type{Real})
true
#
Core.DataType
— Type
DataType <: Type{T}
'DataType` represents explicitly declared types with names, explicitly declared supertypes, and (optionally) parameters. Each specific value in the system is an instance of some type of `DataType'.
Examples
julia> typeof(Real)
DataType
julia> typeof(Int)
DataType
julia> struct Point
x::Int
y
end
julia> typeof(Point)
DataType
#
Core.:<:
— Function
<:(T1, T2)
The subtype operator: returns true
if and only if all values of type T1
are also of type `T2'.
Examples
julia> Float64 <: AbstractFloat
true
julia> Vector{Int} <: AbstractArray
true
julia> Matrix{Float64} <: Matrix{AbstractFloat}
false
#
Base.typejoin
— Function
typejoin(T, S, ...)
Returns the closest common ancestor of the types T
and `S', that is, the narrowest type from which they both inherit. Performs recursion on additional arguments with a variable number.
Examples
julia> typejoin(Int, Float64)
Real
julia> typejoin(Int, Float64, ComplexF32)
Number
#
Base.typeintersect
— Function
typeintersect(T::Type, S::Type)
Calculates the type that contains the intersection of the types T
and S
. This is usually the narrowest type or the closest to it.
A special case in which exact behavior is guaranteed: for T <: S
, typeintersect(S, T) == T == typeintersect(T, S)
.
#
Base.promote_type
— Function
promote_type(type1, type2, ...)
Promotion refers to the conversion of values of mixed types into one common type. The promote_type
represents the default promotion method in Julia, when operators (usually mathematical ones) receive arguments of different types. As a rule, the promote_type
function tries to return a type that allows at least approximately expressing most of the values of each of the input types without unnecessary expansion. Some losses are acceptable. For example, promote_type(Int64, Float64)
returns Float64
, although, strictly speaking, not all values Int64
can be represented exactly as the values of `Float64'.
See also the description promote
, promote_typejoin
, promote_rule
.
Examples
julia> promote_type(Int64, Float64)
Float64
julia> promote_type(Int32, Int64)
Int64
julia> promote_type(Float32, BigInt)
BigFloat
julia> promote_type(Int16, Float16)
Float16
julia> promote_type(Int64, Float16)
Float16
julia> promote_type(Int8, UInt16)
UInt16
!!! warning "Don’t overload this directly"
To overload the promotion for your own type, overload the function promote_rule
. The function promote_rule
is called inside promote_type' to determine the type. If you overload `promote_type
directly, errors may occur due to ambiguity.
#
Base.promote_typejoin
— Function
promote_typejoin(T, S)
Calculates a type that contains both type T
and type S'. The resulting type can be either the parent of both input types, or their Union. It uses as a backup option `typejoin
.
See also the function description promote
and promote_type
.
Examples
julia> Base.promote_typejoin(Int, Float64)
Real
julia> Base.promote_type(Int, Float64)
Float64
#
Base.isdispatchtuple
— Function
isdispatchtuple(T)
Determines whether the type T
is the "final type" of the tuple, that is, it can be used as a type signature during dispatch and has no subtypes (or supertypes) that could be used in the call. If 'T` is not a type, returns `false'.
Declared structure
#
Base.ismutable
— Function
ismutable(v) -> Bool
Returns true
if and only if the value of v
is changeable. In the section Mutable composite types discusses the concept of mutability in detail. Note that this function works with values, so if you pass it the 'DataType` type, it will determine that the value type is mutable.
For technical reasons, |
See also the description isbits'
and `isstructtype.
Examples
julia> ismutable(1)
false
julia> ismutable([1,2])
true
Compatibility: Julia 1.5
This feature requires a Julia version at least 1.5. |
#
Base.isimmutable
— Function
isimmutable(v) -> Bool
We recommend using the |
Examples
julia> isimmutable(1)
true
julia> isimmutable([1,2])
false
#
Base.ismutabletype
— Function
ismutabletype(T) -> Bool
Determines whether the type T
has been declared mutable (i.e. using the keyword mutable struct'). If 'T
is not a type, returns `false'.
Compatibility: Julia 1.7
This feature requires a version of Julia at least 1.7. |
#
Base.isabstracttype
— Function
isabstracttype(T)
Determines whether the type T
was declared as abstract (i.e. using the syntax abstract type'). Note that this is not a negation of `isconcretetype(T)'. If 'T
is not a type, it returns `false'.
Examples
julia> isabstracttype(AbstractArray)
true
julia> isabstracttype(Vector)
false
#
Base.isprimitivetype
— Function
isprimitivetype(T) -> Bool
Determines whether the type T
was declared as primitive (i.e. using the syntax primitive type'). If 'T
is not a type, it returns `false'.
#
Base.issingletontype
— Function
Base.issingletontype(T)
Determines whether the type T
can have only one instance, as, for example, in the case of a field-less structure type with the exception of other single values. If 'T` is not a specific type, returns `false'.
#
Base.isstructtype
— Function
isstructtype(T) -> Bool
Determines whether the type T
was declared as a structure type (i.e. with the keyword struct
or mutable struct
). If 'T` is not a type, returns `false'.
#
Base.nameof
— Method
nameof(t::DataType) -> Symbol
Returns the name of the DataType
type (possibly encapsulated in `unionAll', without the name of the parent module) as a character.
Examples
julia> module Foo
struct S{T}
end
end
Foo
julia> nameof(Foo.S{T} where T)
:S
#
Base.fieldnames
— Function
fieldnames(x::DataType)
Returns a tuple with the names of fields of type `DataType'.
See also the description propertynames
and hasfield
.
Examples
julia> fieldnames(Rational)
(:num, :den)
julia> fieldnames(typeof(1+im))
(:re, :im)
#
Base.fieldname
— Function
fieldname(x::DataType, i::Integer)
Returns the name of a field with the index i
of the type `DataType'.
Examples
julia> fieldname(Rational, 1)
:num
julia> fieldname(Rational, 2)
:den
#
Core.fieldtype
— Function
fieldtype(T, name::Symbol | index::Int)
Defines the declared type of the field (specified by name or index) in the composite DataType T
.
Examples
julia> struct Foo
x::Int64
y::String
end
julia> fieldtype(Foo, :x)
Int64
julia> fieldtype(Foo, 2)
String
#
Base.fieldtypes
— Function
fieldtypes(T::Type)
Returns the declared types of all fields of the composite DataType T
as a tuple.
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
Examples
julia> struct Foo
x::Int64
y::String
end
julia> fieldtypes(Foo)
(Int64, String)
#
Base.fieldcount
— Function
fieldcount(t::Type)
Returns the number of fields that an instance of the specified type will have. If the type is too abstract to define this value, an error occurs.
#
Base.hasfield
— Function
hasfield(T::Type, name::Symbol)
Returns a boolean value indicating whether type T
has its own 'name` field.
See also the description fieldnames
, fieldcount'
and `hasproperty.
Compatibility: Julia 1.2
This feature requires a Julia version of at least 1.2. |
Examples
julia> struct Foo
bar::Int
end
julia> hasfield(Foo, :bar)
true
julia> hasfield(Foo, :x)
false
#
Core.nfields
— Function
nfields(x) -> Int
Returns the number of fields for the specified object.
Examples
julia> a = 1//2;
julia> nfields(a)
2
julia> b = 1
1
julia> nfields(b)
0
julia> ex = ErrorException("I've done a bad thing");
julia> nfields(ex)
1
In these examples, a
is of type Rational
, which has two fields. Field b
is of type Int
— a primitive bit type without fields. The ex
field has the type ErrorException
with one field.
#
Base.isconst
— Function
isconst(m::Module, s::Symbol) -> Bool
Determines whether a global variable is declared as const' in the 'm
module.
isconst(t::DataType, s::Union{Int,Symbol}) -> Bool
Determines whether the field s
is declared as const' in the type `t
.
#
Base.isfieldatomic
— Function
isfieldatomic(t::DataType, s::Union{Int,Symbol}) -> Bool
Determines whether the 's` field is declared as @atomic
in the t
type.
Location in memory
#
Base.sizeof
— Method
sizeof(T::DataType)
sizeof(obj)
The size in bytes of the canonical binary representation of the specified type DataType
T
, if any. Or the size in bytes of the obj
object, if it is not of the `DataType' type.
See also the description Base.summarysize
.
Examples
julia> sizeof(Float32)
4
julia> sizeof(ComplexF64)
16
julia> sizeof(1.0)
8
julia> sizeof(collect(1.0:10.0))
80
julia> struct StructWithPadding
x::Int64
flag::Bool
end
julia> sizeof(StructWithPadding) # не сумма `sizeof` полей из-за заполнения
16
julia> sizeof(Int64) + sizeof(Bool) # отличается от приведенного выше
9
If the 'DataType` T
type does not have a specific size, an error occurs.
julia> sizeof(AbstractArray)
ERROR: Abstract type AbstractArray does not have a definite size.
Stacktrace:
[...]
#
Base.isconcretetype
— Function
isconcretetype(T)
Determines whether the type T
is specific, that is, it can have direct instances (values of x
such that typeof(x) ===T
). Note that this is not a negation of isabstracttype(T)'. If 'T
is not a type, returns `false'.
See also the description isbits
, isabstracttype
, issingletontype
.
Examples
julia> isconcretetype(Complex)
false
julia> isconcretetype(Complex{Float32})
true
julia> isconcretetype(Vector{Complex})
true
julia> isconcretetype(Vector{Complex{Float32}})
true
julia> isconcretetype(Union{})
false
julia> isconcretetype(Union{Int,String})
false
#
Base.isbitstype
— Function
isbitstype(T)
Returns true
if T
is a simple data type, that is, immutable and does not contain references to values other than values of the primitive
and isbitstype
types. A classic example is numeric types such as UInt8
, Float64
and Complex{Float64}
. This category of types is of particular importance, since they can be used as type parameters and may not track the status. isdefined
or isassigned
and have a specific structure compatible with the C language. If 'T` is not a type, it returns `false'.
See also the description isbits
, isprimitivetype
and ismutable
.
Examples
julia> isbitstype(Complex{Float64})
true
julia> isbitstype(Complex)
false
#
Base.fieldoffset
— Function
fieldoffset(type, i)
Returns the byte offset of the field with the type i
index relative to the beginning of the data. For example, using this function, you can get summary information about the structure as follows.
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
— Function
Base.datatype_alignment(dt::DataType) -> Int
The minimum alignment of the allocated memory area for instances of this type. You can call isconcretetype
for any type, but for an object in memory, the alignment of the elements is returned, not the entire object.
#
Base.datatype_haspadding
— Function
Base.datatype_haspadding(dt::DataType) -> Bool
Determines whether the fields of instances of this type are placed in memory without intermediate padding bits (defined as bits whose values do not have a unique effect on the equality check when applied to the fields of the structure). It can be called for any type of `isconcretetype'.
#
Base.datatype_pointerfree
— Function
Base.datatype_pointerfree(dt::DataType) -> Bool
Determines whether instances of this type can contain references to memory controlled by the garbage collector. It can be called for any type of `isconcretetype'.
Special values
#
Base.typemin
— Function
typemin(T)
The minimum value that can be represented by the specified (real) numeric DataType T
.
Examples
julia> typemin(Int8)
-128
julia> typemin(UInt32)
0x00000000
julia> typemin(Float16)
-Inf16
julia> typemin(Float32)
-Inf32
julia> nextfloat(-Inf32) # минимальное конечное число с плавающей запятой типа Float32
-3.4028235f38
#
Base.typemax
— Function
typemax(T)
The maximum value that can be represented by the specified (real) numeric type `DataType'.
Examples
julia> typemax(Int8)
127
julia> typemax(UInt32)
0xffffffff
julia> typemax(Float64)
Inf
julia> typemax(Float32)
Inf32
julia> floatmax(Float32) # максимальное конечное число с плавающей запятой типа Float32
3.4028235f38
#
Base.floatmin
— Function
floatmin(T = Float64)
Returns the minimum positive normal number that can be represented by the floating-point type `T'.
Examples
julia> floatmin(Float16)
Float16(6.104e-5)
julia> floatmin(Float32)
1.1754944f-38
julia> floatmin()
2.2250738585072014e-308
#
Base.floatmax
— Function
floatmax(T = Float64)
Returns the maximum finite number that can be represented by the floating-point type `T'.
Examples
julia> floatmax(Float16)
Float16(6.55e4)
julia> floatmax(Float32)
3.4028235f38
julia> floatmax()
1.7976931348623157e308
julia> typemax(Float64)
Inf
#
Base.maxintfloat
— Function
maxintfloat(T=Float64)
The maximum consecutive floating-point integer that can be accurately represented by the specified floating-point type T
(default is Float64
).
In other words, the maxintfloat' function returns the minimum positive floating-point integer `n
such that n+1
cannot be accurately represented by the type T
.
If you need an integer value (Integer
), use Integer(maxintfloat(T))
.
maxintfloat(T, S)
The maximum consecutive integer that can be represented by the specified floating-point type T
and not more than the maximum integer that can be represented by the integer type S
. Or, equivalently, this is the minimum of the values of maxintfloat(T)
and typemax(S)
.
#
Base.eps
— Method
eps(::Type{T}) where T<:AbstractFloat
eps()
Returns a machine epsilon of the floating-point type T
(by default, T = Float64
). It is defined as the interval between 1 and the next maximum value, which can be represented by the type typeof(one(T))
. Equivalent to eps(one(T))
. (Since the value of eps(T)
is the margin of relative error for the type T
, it is a dimensionless quantity, just like one
.)
Examples
julia> eps()
2.220446049250313e-16
julia> eps(Float32)
1.1920929f-7
julia> 1.0 + eps()
1.0000000000000002
julia> 1.0 + eps()/2
1.0
#
Base.eps
— Method
eps(x::AbstractFloat)
Returns the unit of least precision (ulp) for the value x
. This is the distance between consecutive representable floating point values with the value x'. In most cases, if the distance on the two sides of the `x
is different, the larger of them is taken, that is
eps(x) == max(x-prevfloat(x), nextfloat(x)-x)
The exceptions to this rule are the minimum and maximum end values (for example, nextfloat(-Inf)
and prevfloat(Inf)
for the type Float64
), for which rounding is performed to the smallest of the distances.
This is justified by the fact that the eps function limits the rounding error of floating-point numbers. In the default rounding mode, `RoundNearest' if — a real number, and — the floating-point number closest to Then
See also the description nextfloat
, issubnormal
, floatmax
.
Examples
julia> eps(1.0)
2.220446049250313e-16
julia> eps(prevfloat(2.0))
2.220446049250313e-16
julia> eps(2.0)
4.440892098500626e-16
julia> x = prevfloat(Inf) # максимальное конечное значение Float64
1.7976931348623157e308
julia> x + eps(x)/2 # округление в большую сторону
Inf
julia> x + prevfloat(eps(x)/2) # округление в меньшую сторону
1.7976931348623157e308
#
Base.instances
— Function
instances(T::Type)
Returns a collection of all instances of the specified type, if applicable. It is mainly used for enumerated types (see @enum
).
Examples
julia> @enum Color red blue green
julia> instances(Color)
(red, blue, green)
Special types
#
Core.Any
— Type
Any::DataType
Any
is a union of all types. It has the characteristic property isa(x, Any) == true
for any x'. Thus, `Any
describes the totality of possible values. For example, Integer
is a subset of type Any
, including Int
, Int8
and other integer types.
#
Core.Union
— Type
Union{Types...}
A union of types is an abstract type that includes all instances of all argument types. This means that T <: Union{T,S}
and S <: Union{T,S}
.
As with other abstract types, it is impossible to create an instance of it, even if all its arguments are not abstract.
Examples
julia> IntOrString = Union{Int,AbstractString}
Union{Int64, AbstractString}
julia> 1 isa IntOrString # экземпляр Int включен в объединение
true
julia> "Hello!" isa IntOrString # String также включен
true
julia> 1.0 isa IntOrString # Float64 не включен, так как не является ни Int, ни AbstractString
false
Advanced Help
Unlike most other parametric types, unions are covariant in their parameters. For example, Union{Real, String}
is a subtype of Union{Number, AbstractString}
.
Empty association Union{}
is the lowest type in Julia.
#
Union{}
— Keyword
Union{}
Union{}
, то есть пустое объединение (Union
) типов, — это тип без значений. Иными словами, оно имеет характерное свойство isa(x, Union{}) == false
for any x
. The alias Base
is defined for the Union{} union.Bottom`, and its type is Core.TypeofBottom
.
Examples
julia> isa(nothing, Union{})
false
#
Core.UnionAll
— Type
UnionAll
Combining types by all values of a type parameter. unionAll
is used to describe parametric types in which the values of some parameters are unknown. For more information, see the section of the manual on types of unionAll.
Examples
julia> typeof(Vector)
UnionAll
julia> typeof(Vector{Int})
DataType
#
Core.Tuple
— Type
Tuple{Types...}
A tuple is a fixed-length container that can contain any values of various types, but cannot be changed (it is immutable). The values can be accessed by indexes. Tuple literals are written comma-separated in 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 tuple of unit length must be written with a comma, (1,)
, and (1)
will just be the value in parentheses. ()
represents an empty tuple (with length 0).
A tuple can be created based on an iterator using the Tuple
type as a 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 of Tuple{Any}
. Therefore, Tuple{Any}
is considered an abstract type, and tuple types are concrete only if their parameters are such. Tuples do not have field names; fields are accessible only by indexes. Tuple types can have any number of parameters.
See the section of the manual dedicated to tuple types.
See also the description Vararg
, NTuple
, ntuple
, tuple
, NamedTuple
.
#
Core.NamedTuple
— Type
NamedTuple
NamedTuple', as the name implies, is a named tuple (`Tuple
). That is, it is a tuple-like collection of values, each element of which has a unique name represented by Symbol
. Like the Tuple
type, the `NamedTuple' type is immutable: neither names nor values can be changed directly after creation.
A named tuple can be created as a literal tuple with keys, for example (a=1, b=2)
, as a literal tuple with a semicolon after the opening parenthesis, for example (; a=1, b=2)
(this form also accepts programmatically generated names, as described below), or using the type NamedTuple' as a constructor, for example `NamedTuple{(:a, :b)}1,2
.
You can access the value associated with a name in a named tuple using the field access syntax, for example x.a
, or using the function getindex'
, for example `x[:a] or x[(:a, :b)]
. The tuple of names can be obtained using the function keys
, and a tuple of values using the function values
.
When iterating over the |
It is convenient to declare NamedTuple
types using a macro. @NamedTuple
.
Examples
julia> x = (a=1, b=2)
(a = 1, b = 2)
julia> x.a
1
julia> x[:a]
1
julia> x[(:a,)]
(a = 1,)
julia> keys(x)
(:a, :b)
julia> values(x)
(1, 2)
julia> collect(x)
2-element Vector{Int64}:
1
2
julia> collect(pairs(x))
2-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 2
Just as in the case of programmatically defining named arguments, a named tuple can be created by specifying the pairs name::Symbol => value
after the semicolon inside the tuple literal. This option and the syntax name=value
can be combined.:
julia> (; :a => 1, :b => 2, c=3)
(a = 1, b = 2, c = 3)
Name-value pairs can also be provided by unpacking a named tuple or any iterator that produces collections of two values, the first of which is a character.:
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) # последнее b перезаписывает значение из nt1
(a = 1, b = 20, c = 3, d = 4)
julia> (; zip(keys, values)...) #zip outputs tuples like (:a, 1)
(a = 1, b = 2, c = 3)
As with named arguments, identifiers and dot expressions assume the use of names.:
julia> x = 0
0
julia> t = (; x)
(x = 0,)
julia> (; t.x)
(x = 0,)
Compatibility: Julia 1.5
Starting with Julia 1.5, implicit names are available for identifiers and dot expressions. |
Compatibility: Julia 1.7
Starting from Julia 1.7, the |
#
Base.@NamedTuple
— Macro
@NamedTuple{key1::Type1, key2::Type2, ...}
@NamedTuple begin key1::Type1; key2::Type2; ...; end
This macro provides a more convenient syntax for declaring NamedTuple
types. It returns the type NamedTuple
with the specified keys and types, which is equivalent to the expression NamedTuple{(:key1, :key2, ...), Tuple{Type1,Type2,...}}
. If the ::Type
declaration is omitted, the Any
type is assumed. The 'begin ... end` form allows you to split the declarations into several lines (just like in the case of the struct
declaration). Otherwise, this form is no different. The macro NamedTuple' is used when outputting `NamedTuple
types, for example, in REPL.
For example, the tuple (a=3.1, b="hello")
has the type NamedTuple{(:a, :b), Tuple{Float64, String}}
. Using the macro @NamedTuple
, it can be declared like this:
julia> @NamedTuple{a::Float64, b::String}
@NamedTuple{a::Float64, b::String}
julia> @NamedTuple begin
a::Float64
b::String
end
@NamedTuple{a::Float64, b::String}
Compatibility: Julia 1.5
This macro was first implemented in Julia 1.5. |
#
Base.@Kwargs
— Macro
@Kwargs{key1::Type1, key2::Type2, ...}
This macro provides a convenient way to construct a representation of the type of named arguments using the same syntax as @NamedTuple
. For example, if you have a function call func([positional arguments]; kw1=1.0, kw2="2")
, you can use this macro to create an internal representation of the named arguments type in the form of @Kwargs{kw1::Float64, kw2::String}
. The macro syntax is specifically designed to simplify the signature type of a method with named arguments when it is output in a stack trace representation.
julia> @Kwargs{init::Int} # внутреннее представление именованных аргументов
Base.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:237
Stacktrace:
[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
Compatibility: Julia 1.10
This macro was first implemented in Julia 1.10. |
#
Base.Val
— Type
Val(c)
Returns the type Val{c}()
, which does not contain run-time data. Such types can be used to transfer information between functions by using the value c
, which should be of type isbits
or `Symbol'. The purpose of this design is to be able to dispatch constants directly (at compile time) without having to check their values at runtime.
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
— Constant
Vararg{T,N}
The last parameter of the tuple type Tuple
can have a special value of Vararg
, which means any number of elements at the end. The expression Vararg{T,N}
matches exactly N
elements of type T'. Finally, the expression `+Vararg{T}+
corresponds to zero or more elements of type T'. Tuple types with the `Vararg
parameter are used to represent arguments accepted by methods with a variable number of arguments (see the manual section on functions with a variable number of arguments).
See also the description NTuple
.
Examples
julia> mytupletype = Tuple{AbstractString, Vararg{Int}}
Tuple{AbstractString, Vararg{Int64}}
julia> isa(("1",), mytupletype)
true
julia> isa(("1",1), mytupletype)
true
julia> isa(("1",1,2), mytupletype)
true
julia> isa(("1",1,2,3.0), mytupletype)
false
#
Base.isnothing
— Function
isnothing(x)
Returns true
if x === nothing
, and false
otherwise.
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
See also the description something
, Base.notnothing'
and `ismissing.
#
Base.notnothing
— Function
notnothing(x)
Causes an error if x === nothing
, and returns x
otherwise.
#
Base.something
— Function
something(x...)
Returns the first of the argument values that is not equal to nothing
, if any. Otherwise, an error occurs. Type arguments Some
are not packaged.
See also the description coalesce
, skipmissing
and @something
.
Examples
julia> something(nothing, 1)
1
julia> something(Some(1), nothing)
1
julia> something(Some(nothing), 2) === nothing
true
julia> something(missing, nothing)
missing
julia> something(nothing, nothing)
ERROR: ArgumentError: No value arguments present
#
Base.@something
— Macro
@something(x...)
Shortened version of the function something
.
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`")
1
julia> 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 === nothing
true
Compatibility: Julia 1.7
This macro was first implemented in Julia 1.7. |
#
Base.Enums.@enum
— Macro
@enum EnumName[::BaseType] value1[=x] value2[=y]
Creates a subtype of Enum{BaseType}
with the name EnumName
and the enumeration elements value1
and value2
, which can be assigned the values x
and y
, respectively. EnumName can be used in the same way as any other type, and the values of enumeration elements can be used as normal values.
Examples
julia> @enum Fruit apple=1 orange=2 kiwi=3
julia> 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
Enumeration elements can also be specified inside the begin
block, for example:
@enum EnumName begin
value1
value2
end
The base type is BaseType' (by default `Int32
) must be a primitive subtype of the type Integer'. The values of the elements can be converted between the enumeration type and the `BaseType'. `read
and write
perform these transformations automatically. If an enumeration is created with a BaseType
type other than the default type, Integer(value1)
returns the integer value value1
with the BaseType
type.
To get a list of all instances of an enumeration, use the instances
function, for example:
julia> instances(Fruit)
(apple, orange, kiwi)
You can construct a symbol from an enumeration instance:
julia> Symbol(apple)
:apple
#
Core.Expr
— Type
Expr(head::Symbol, args...)
A type representing compound expressions in the analyzed Julia code (AST). Each expression consists of a 'head` part, a Symbol
, which specifies the type of expression (for example, a call, a for loop, a conditional operator, etc.), and subexpressions (for example, call arguments). The subexpressions are stored in the Vector' field{Any}
with the name `args'.
See the manual’s chapter on metaprogramming and the developer documentation section dedicated to the AST syntax in Julia.
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
— Type
Symbol
The type of object used to represent identifiers in the analyzed Julia code (AST). It is also often used as a name or label to identify an entity (for example, as a dictionary key). The Symbol
object can be entered using the quote operator :
:
julia> :name
:name
julia> typeof(:name)
Symbol
julia> x = 42
42
julia> eval(:x)
42
Objects of type Symbol
can also be created from strings or other values by calling the constructor Symbol(x...)
.
Symbols (Symbol
) are immutable, and their implementation uses the same object for all symbols (Symbol
) with the same name.
Unlike strings, a Symbol
is an "atomic" or "scalar" entity that does not support character iteration.
#
Core.Module
— Type
Module
Module' is a separate global workspace of variables. For more information, see the keyword description. `module
and the module section of the manual.
Module(name::Symbol=:anonymous, std_imports=true, default_names=true)
Returns the module with the specified name. baremodule
corresponds to the call `Module(:ModuleName, false)'.
An empty module that does not contain a single name can be created by calling Module(:ModuleName, false, false)
. The Base
or Core
modules are not imported into it, and it does not contain a reference to itself.
Universal functions
#
Core.Function
— Type
Function
An abstract type for all functions.
Examples
julia> isa(+, Function)
true
julia> typeof(sin)
typeof(sin) (singleton type of function sin, subtype of Function)
julia> ans <: Function
true
#
Base.hasmethod
— Function
hasmethod(f, t::Type{<:Tuple}[, kwnames]; world=get_world_counter()) -> Bool
Determines whether a given universal function has a method corresponding to the specified tuple of argument types, with the upper bound of the "age of the world" (hierarchy of method definitions) specified in the "world` argument.
If a tuple of named argument names kwnames
is provided, the method f
corresponding to type t
is also checked for these names. If a method accepts a variable number of named arguments, for example by using kwargs...
, all names in kwnames
are considered appropriate. Otherwise, the specified names must be a subset of the named arguments of the method.
See also the description applicable
.
Compatibility: Julia 1.2
To specify the names of named arguments, a version of Julia at least 1.2 is required. |
Examples
julia> hasmethod(length, Tuple{Array})
true
julia> f(; oranges=0) = oranges;
julia> hasmethod(f, Tuple{}, (:oranges,))
true
julia> hasmethod(f, Tuple{}, (:apples, :bananas))
false
julia> g(; xs...) = 4;
julia> hasmethod(g, Tuple{}, (:a, :b, :c, :d)) # g принимает произвольное число именованных аргументов
true
#
Core.applicable
— Function
applicable(f, args...) -> Bool
Determines whether the specified universal function has a method applicable to the specified arguments.
See also the description hasmethod
.
Examples
julia> function f(x, y)
x + y
end;
julia> applicable(f, 1)
false
julia> applicable(f, 1, 2)
true
#
Base.isambiguous
— Function
Base.isambiguous(m1, m2; ambiguous_bottom=false) -> Bool
Determines whether two methods m1
and m2
can be ambiguous for some call signature. This check is performed in the context of other methods of the same function: the methods m1
and m2
themselves may be ambiguous, but if a third method is defined that resolves the ambiguity, the value false' is returned. Conversely, the methods `m1
and m2
can be ordered by themselves, but if the third method cannot be sorted together with them, ambiguity arises in the aggregate.
For parametric types, the named argument ambiguous_bottom
determines whether the union Union{}
is considered an ambiguous intersection of type parameters: when set to true
it is considered ambiguous, but if the value is false
, it is not.
Examples
julia> foo(x::Complex{<:Integer}) = 1
foo (generic function with 1 method)
julia> foo(x::Complex{<:Rational}) = 2
foo (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)
true
julia> Base.isambiguous(m1, m2, ambiguous_bottom=false)
false
#
Core.invoke
— Function
invoke(f, argtypes::Type, args...; kwargs...)
Calls the method of the specified universal function f
, which corresponds to the specified types argtypes
, passing arguments args
and named arguments kwargs'. The `args
arguments must match the types specified in `argtypes', meaning no automatic conversion is performed. This function allows you to call a method that is not the most specific, which is useful in cases where the behavior of a more general definition is explicitly required (often as part of the implementation of a more specific method of the same function).
When using invoke
to call functions that are written by someone else, be careful. The definition used for the specified types of argtypes' depends on the internal implementation, unless it is explicitly stated that the call with certain types of `argtypes
is part of the public API. For example, in the example below, the functions f1
and f2
will usually be interchangeable, since there is no difference between them during a normal call (not using invoke
). However, this difference becomes noticeable when using `invoke'.
Examples
julia> f(x::Real) = x^2;
julia> f(x::Integer) = 1 + invoke(f, Tuple{Real}, x);
julia> f(2)
5
julia> f1(::Integer) = Integer
f1(::Real) = Real;
julia> f2(x::Real) = _f2(x)
_f2(::Integer) = Integer
_f2(_) = Real;
julia> f1(1)
Integer
julia> f2(1)
Integer
julia> invoke(f1, Tuple{Real}, 1)
Real
julia> invoke(f2, Tuple{Real}, 1)
Integer
#
Base.@invoke
— Macro
@invoke f(arg::T, ...; kwargs...)
Provides a convenient way to call invoke
by extending @invoke f(arg1::T1, arg2::T2; kwargs...)+`before `+invoke(f, Tuple{T1,T2}, arg1, arg2; kwargs...)
. If the annotation of the argument type is not specified, it is replaced by the Core' type.Typeof
of this argument. To call a method whose argument is not typed or explicitly typed as Any', annotate the argument with `::Any
.
In addition, the following syntax is supported:
-
@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 % Unsigned
0x00000000000001a4
julia> @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))
Compatibility: Julia 1.7
This macro requires a Julia version of at least 1.7. |
Compatibility: Julia 1.9
This macro has been exported since version Julia 1.9. |
Compatibility: Julia 1.10
The additional syntax has been supported since Julia 1.10. |
#
Base.invokelatest
— Function
invokelatest(f, args...; kwargs...)
Calls f(args...; kwargs...)
, but guarantees the execution of the most recent method f
. This is useful in special situations, such as when executing long event loops or callback functions that may invoke outdated versions of the f
function. (The disadvantage is that the invokelatest
function is slightly slower than the direct call to f
, and the result type cannot be inferred by the compiler.)
Compatibility: Julia 1.9
Prior to Julia 1.9, this function was not exported and was called in the form of `Base.invokelatest'. |
#
Base.@invokelatest
— Macro
@invokelatest f(args...; kwargs...)
Provides a convenient way to call invokelatest
. @invokelatest f(args...; kwargs...)
just expands to Base.invokelatest(f, args...; kwargs...)
.
In addition, the following syntax is supported:
-
@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))
Compatibility: Julia 1.7
This macro requires a Julia version of at least 1.7. |
Compatibility: Julia 1.9
Prior to Julia 1.9, this macro was not exported and was called in the |
Compatibility: Julia 1.10
For the additional syntax of |
#
new
— Keyword
new, or new{A,B,...}
A special function that is available to internal constructors and creates a new object of the type. When using the new form{A,B,…} parameter values for parametric types are specified explicitly. For more information, see the section of the manual on methods of internal constructors .
#
Base.:|>
— Function
|>(x, f)
An infix operator that applies the function f
to the argument x'. This allows you to write `f(g(x))`in the form of `x |> g |> f
. When using anonymous functions, it is usually necessary to enclose the definition in parentheses in order to get the desired chain.
Examples
julia> 4 |> inv
0.25
julia> [2, 3, 5] |> sum |> inv
0.1
julia> [0 1; 2 3] .|> (x -> x^2) |> sum
14
#
Base.:∘
— Function
f ∘ g
Function composition: (f ∘ g)(args...; kwargs...)
means f(g(args...; kwargs...))
. The character ∘
can be added to Julia’s REPL (and most editors configured accordingly) by typing \circ<tab>
.
Function composition is also possible in prefix form: ∘(f, g)
is equivalent to f ∘ g
. The prefix form supports the composition of several functions (∘(f, g, h) = f ∘ g ∘ h
) and decompression (∘(fs...)
) to create an iterable collection of functions. The last argument for ∘
is executed first.
Compatibility: Julia 1.4
The composition of several functions requires a Julia version of at least 1.4. |
Compatibility: Julia 1.5
The composition of a single function ∘(f) requires a Julia version of 1.5 or higher. |
Compatibility: Julia 1.7
A version of Julia at least 1.7 is required to use named arguments. |
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
1
julia> fs = [
x -> 2x
x -> x-1
x -> x/2
x -> x+1
];
julia> ∘(fs...)(3)
2.0
See also the description ComposedFunction
and !f::Function
.
#
Base.ComposedFunction
— Type
ComposedFunction{Outer,Inner} <: Function
Represents the composition of two called objects outer::Outer
and inner::Inner
. That is
ComposedFunction(outer, inner)(args...; kw...) === outer(inner(args...; kw...))
To create an instance of the ComposedFunction
type, it is preferable to use the composition operator. ∘
:
julia> sin ∘ cos === ComposedFunction(sin, cos)
true
julia> typeof(sin∘cos)
ComposedFunction{typeof(sin), typeof(cos)}
The components of the composition are stored in the fields of the 'ComposedFunction` object. They can be accessed as follows.
julia> composition = sin ∘ cos
sin ∘ cos
julia> composition.outer === sin
true
julia> composition.inner === cos
true
Compatibility: Julia 1.6
To use the ComposedFunction type, Julia version 1.6 or higher is required. In earlier versions, the |
See also the description ∘
.
#
Base.splat
— Function
splat(f)
Equivalent to
my_splat(f) = args->f(args...)
that is, if a function is given, it returns a new function that takes one argument and decompresses it into the original function. This can be useful if you need to pass a function with multiple arguments in a context where a single argument is expected; but a tuple is passed as that argument.
Examples
julia> map(splat(+), zip(1:3,4:6))
3-element Vector{Int64}:
5
7
9
julia> my_add = splat(+)
splat(+)
julia> my_add((1,2,3))
6
#
Base.Fix2
— Type
Fix2(f, x)
A type representing a function with two arguments f
, which is partially applied: the second argument has a fixed value of x. In other words, Fix2(f, x)
acts similarly to y->f(y, x)
.
Syntax
#
Core.eval
— Function
Core.eval(m::Module, expr)
Evaluates the expression in the specified module and returns the result.
#
eval
— Function
eval(expr)
Evaluates an expression in the global scope of the containing module. Each Module' (except those declared with the keyword `baremodule
) has its own definition of the eval
function with one argument, which evaluates expressions in this module.
#
Base.@eval
— Macro
@eval [mod,] ex
Evaluates an expression with values that are interpolated into it using the `eval' function. If two arguments are specified, the first one contains the module in which the calculation is to be performed.
#
Base.evalfile
— Function
evalfile(path::AbstractString, args::Vector{String}=String[])
Uploads the file to an anonymous module using the function include
, evaluates all expressions and returns the value of the last one. The optional argument args
can be used to specify the input arguments of the script (i.e. the global variable `ARGS'). Please note that definitions (for example, methods, global objects) are processed in an 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> x
2
julia> rm("testfile.jl")
#
Base.@inbounds
— Macro
@inbounds(blk)
Disables checking the boundaries of arrays in expressions.
In the example below, the range entry check is skipped when accessing element i
of array A
to improve performance.
function sum(A::AbstractArray)
r = zero(eltype(A))
for i in eachindex(A)
@inbounds r += A[i]
end
return r
end
When using the |
#
Base.@boundscheck
— Macro
@boundscheck(blk)
Marks the expression blk
as a boundary check block, so it can be ignored by the block. @inbounds
.
The function in which the |
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 scope
julia> f2()
"accessing (1:2)[-1]"
The |
#
Base.@propagate_inbounds
— Macro
@propagate_inbounds
Instructs the compiler to embed the function while preserving the context of the occurrence in the range of the calling object.
#
Base.@inline
— Macro
@inline
Gives the compiler an indication that this function can be embedded.
Small functions usually do not require the @inline
annotation, as the compiler embeds them automatically. By using @inline
for more complex functions, you can give the compiler an additional signal to embed them.
The macro @inline
can be applied immediately before the function definition or in its body.
# аннотирование полного определения
@inline function longdef(x)
...
end
# аннотирование краткого определения
@inline shortdef(x) = ...
# аннотирование анонимной функции, создаваемой с помощью блока `do`
f() do
@inline
...
end
Compatibility: Julia 1.8
A Julia version of at least 1.8 is required for use in the function body. |
@inline block
Gives the compiler an indication that calls inside the `block' block can be embedded.
# Компилятор попытается встроить `f`
@inline f(...)
# Компилятор попытается встроить `f`, `g` и `+`
@inline f(...) + g(...)
The annotation at the call location always takes precedence over the annotation applied to the definition of the function being called.: |
@noinline function explicit_noinline(args...)
# тело
end
let
@inline explicit_noinline(args...) # будет встроено
end
If there are nested annotations in the call location, the most deeply nested one takes precedence.: |
@noinline let a0, b0 = ...
a = @inline f(a0) # компилятор попытается встроить этот вызов
b = f(b0) # компилятор НЕ будет пытаться встроить этот вызов
return a, b
end
Although if there is an annotation at the call location, an embed attempt will be made without taking into account the cost model, there is a possibility that embed will not occur. In particular, recursive calls cannot be embedded, even if they are annotated with `@inline'. |
Compatibility: Julia 1.8
To use annotations at the call location, a Julia version of at least 1.8 is required. |
#
Base.@noinline
— Macro
@noinline
Gives the compiler an indication that the function should not be embedded.
Small functions are usually integrated automatically. By applying the macro @noinline
to them, you can prevent this.
The macro @noinline
can be applied immediately before the function definition or in its body.
# аннотирование полного определения
@noinline function longdef(x)
...
end
# аннотирование краткого определения
@noinline shortdef(x) = ...
# аннотирование анонимной функции, создаваемой с помощью блока `do`
f() do
@noinline
...
end
Compatibility: Julia 1.8
A Julia version of at least 1.8 is required for use in the function body. |
@noinline block
Gives the compiler an indication that calls inside the `block' block should not be embedded.
# Компилятор попытается не встраивать `f`
@noinline f(...)
# Компилятор попытается не встраивать `f`, `g` и `+`
@noinline f(...) + g(...)
The annotation at the call location always takes precedence over the annotation applied to the definition of the function being called.: |
@inline function explicit_inline(args...)
# тело
end
let
@noinline explicit_inline(args...) # не будет встроено
end
If there are nested annotations in the call location, the most deeply nested one takes precedence.: |
@inline let a0, b0 = ...
a = @noinline f(a0) # компилятор НЕ будет пытаться встроить этот вызов
b = f(b0) # компилятор попытается встроить этот вызов
return a, b
end
Compatibility: Julia 1.8
To use annotations at the call location, a Julia version of at least 1.8 is required. |
The simplest function (for example, returning a constant) can be embedded, despite the annotation. |
#
Base.@nospecialize
— Macro
@nospecialize
When applied to the function argument name, it instructs the compiler that the method should not be specialized for different types of this argument: the declared type should be used for each argument. It can be applied to an argument in a formal argument list or in the body of a function. When applied to an argument, the macro must cover its entire expression, for example @nospecialize(x::Real)
or @nospecialize(i::Integer...)
, not just the name of the argument. When used in the function body, the macro must be in the operator position before the rest of the code.
When used without arguments, this macro applies to all arguments in the parent scope. In the local scope, this means all arguments of the containing function. In the global area (top level) this means all the methods defined further in the current module.
You can restore the default specialization behavior using a macro @specialize
.
function example_function(@nospecialize x)
...
end
function example_function(x, @nospecialize(y = 1))
...
end
function example_function(x, y, z)
@nospecialize x y
...
end
@nospecialize
f(y) = [x for x in y]
@specialize
The '@nospecialize` macro affects code generation, but not type inference: it limits the variety of the resulting machine code, but does not impose any restrictions (other than standard ones) on type inference. In addition to this, to limit type inference, use |
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 result of the annotation @nospecialize
is the equivalent
f(A::AbstractArray) = invoke(g, Tuple{AbstractArray}, A)
ensuring that only one version of the machine code is generated for g
, which is universal for any AbstractArray' array. However, for both `g
and f
, a specific return type is defined, which is still used to optimize the callers of f
and `g'.
#
Base.@specialize
— Macro
@specialize
Restores the default specialization behavior for the argument. For more information, see @nospecialize
.
#
Base.@nospecializeinfer
— Macro
Base.@nospecializeinfer function f(args...)
@nospecialize ...
...
end
Base.@nospecializeinfer f(@nospecialize args...) = ...
Instructs the compiler to output the type f
using the declared argument types to which the macro `@nospecialize' is applied. It can be used to limit the number of specializations generated by the compiler during output.
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, type f
will be output for each specific type A
, but type g
will be output only once with the declared argument type A::AbstractArray'. This means that the output time by the compiler for it will most likely not increase, since it is impossible to deduce a specific return type. If the macro `@nospecializeinfer
was not used, for f([1.0])`the return type `g
would be Float64', that is, the type output for `+g(::Vector{Float64})+
would have been executed despite the ban on generating specialized code.
Compatibility: Julia 1.10
To use |
#
Base.@constprop
— Macro
Base.@constprop setting [ex]
Controls the mode of interprocedural distribution of constants for an annotated function.
Two setting
values are supported:
-
Base.@constprop :aggressive [ex]
: The propagation of constants is applied in an aggressive mode. For a method whose return type depends on the values of the arguments, this can improve the output results, but at the cost of additional compilation time. -
Base.@constprop :none [ex]
: constant propagation is disabled. This can reduce compilation time for functions that the Julia compiler might otherwise consider suitable for distributing constants. Typical cases are functions with arguments likeBool
or `Symbol' or named arguments.
The Base' macro.@constprop
can be applied immediately before the function definition or in its body.
# аннотирование полного определения
Base.@constprop :aggressive function longdef(x)
...
end
# аннотирование краткого определения
Base.@constprop :aggressive shortdef(x) = ...
# аннотирование анонимной функции, создаваемой с помощью блока `do`
f() do
Base.@constprop :aggressive
...
end
Compatibility: Julia 1.10
A version of Julia at least 1.10 is required for use in the function body. |
#
Base.gensym
— Function
gensym([tag])
Creates a symbol that will not conflict with other variable names (in the same module).
#
Base.@gensym
— Macro
@gensym
Creates a gensym symbol for a variable. For example, @gensym x y
is converted to x = gensym("x"); y = gensym("y")
.
#
var"name"
— Keyword
var
The syntax 'var"example"` allows you to access a variable named Symbol("example")
, even if example
is not a valid name in Julia.
This can be useful for compatibility with programming languages that have different rules for constructing valid names. For example, to access the R
variable named draw.segments
, you can use the expression var"draw.segments"
in the Julia code.
In addition, it is used to display (show
) Julia source code that has undergone hygienic macro processing or otherwise contains variable names that cannot be analyzed in the usual way.
Note that this syntax requires analyzer support, so it is expanded directly by the analyzer, rather than implemented as a regular string macro `@var_str'.
Compatibility: Julia 1.3
A version of Julia at least 1.3 is required to use this syntax. |
#
Base.@goto
— Macro
@goto name
Using the expression @goto name
, an unconditional transition is made to the operator in the location @label name
.
The macros @label
and @goto
do not allow switching to other top-level operators. An error will occur when trying to do this. To use @goto
, enclose the macros @label
and `@goto' in a block.
#
Base.@label
— Macro
@label name
Assigns the symbolic label name
to the operator. The label indicates the end point of an unconditional transition using @goto name
.
#
Base.SimdLoop.@simd
— Macro
@simd
Marks the loop for
, telling the compiler that it can more freely reorder it.
This feature is experimental and may change or disappear in future versions of Julia. Incorrect use of the '@simd` macro can lead to unexpected results. |
The object that is being iterated over in the @simd for
loop must be a one-dimensional range. When using the macro @simd
, several loop properties are asserted.
-
Iterations can be safely performed in any order or with overlap (operations with reduction variables have their own characteristics).
-
The order of floating-point operations performed with reduction variables can be changed or shortened, and the results may not be the same as without using `@simd'.
In many cases, Julia can automatically vectorize internal for loops without using the '@simd` macro. Using @simd
gives the compiler additional freedom, so vectorization becomes possible in other situations as well. In any case, to vectorize the inner loop, it must have the following properties.
-
The loop should be the most deeply nested.
-
The body of the loop should be a linear code. Therefore, currently
@inbounds
required for all accesses to the array. The compiler can sometimes convert short expressions&&
,||
and?:
into linear code if it is safe to evaluate all operands without conditions. You can also use the functionifelse
instead of?:
in the loop, if it is safe to do so. -
Requests must be step-by-step in nature: "build" (reads at an arbitrary index) and "distribution" (writes at an arbitrary index) operations are prohibited.
-
The step of the array must be single.
By default, the |
-
There are no cyclically generated dependencies in memory.
-
Any iteration can move forward without waiting for the previous iteration to complete.
#
Base.@polly
— Macro
@polly
Instructs the compiler to apply the polyhedral Polly optimizer to the function.
#
Base.@generated
— Macro
@generated f
'@generated` marks the function as generated. In the body of the generated function, only the types of arguments are available (but not their values). The function returns a quoted expression that is evaluated when the function is called. The '@generated` macro should not be applied to functions that change the global scope or depend on mutable elements.
For more information, see the chapter on metaprogramming.
Examples
julia> @generated function bar(x)
if x <: Integer
return :(x ^ 2)
else
return :(x)
end
end
bar (generic function with 1 method)
julia> bar(4)
16
julia> bar("baz")
"baz"
#
Base.@assume_effects
— Macro
Base.@assume_effects setting... [ex]
Redefines the compiler’s side-effects model. This macro can be used in several contexts.:
-
immediately before defining a method to redefine the entire side effect model of the applied method;
-
inside the function body without arguments to redefine the entire side-effect model of the enclosing method;
-
applied to a block of code for redefining its local side-effect model.
Examples
julia> Base.@assume_effects :terminates_locally function fact(x)
# вариант использования 1:
# :terminates_locally обеспечивает свертку констант в `fact`
res = 1
0 ≤ x < 20 || error("bad fact")
while x > 1
res *= x
x -= 1
end
return res
end
fact (generic function with 1 method)
julia> code_typed() do
fact(12)
end |> only
CodeInfo(
1 ─ return 479001600
) => Int64
julia> code_typed() do
map((2,3,4)) do x
# вариант использования 2:
# :terminates_locally обеспечивает свертку констант в анонимной функции
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 |> only
CodeInfo(
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")
# use case 3:
# abstract :terminates_locally indicates that the compiler should not perform the analysis
# of the `:terminates' effect in this `while` block, which provides convolution
# constants in the parent anonymous function
Base.@assume_effects :terminates_locally while x > 1
res *= x
x -= 1
end
return res
end
end |> only
CodeInfo(
1 ─ return (2, 6, 24)
) => Tuple{Int64, Int64, Int64}
Compatibility: Julia 1.8
To use |
Compatibility: Julia 1.10
A version of Julia at least 1.10 is required for use in the function body. |
Compatibility: Julia 1.11
Julia version 1.11 or higher is required to annotate code blocks. |
Improper use of this macro can lead to undefined behavior (including crashes, incorrect results, or other hard-to-track errors). Use it with caution and only if absolutely necessary. Even in this case, all possible measures SHOULD be taken to minimize the severity of the side effect statement (for example, do not use |
As a rule, each setting
value makes a statement about the behavior of the function, without requiring the compiler to confirm such a value. Such statements are made for all "ages of the world." Therefore, it is recommended to avoid using generic functions that can later be extended so that statements become invalid (leading to undefined behavior).
The following setting
values are supported:
-
:consistent
-
:effect_free
-
:nothrow
-
:terminates_globally
-
:terminates_locally
-
:notaskstate
-
:inaccessiblememonly
-
:noub
-
:noub_if_noinbounds
-
:nortcall
-
:foldable
-
:removable
-
:total
Advanced Help
:consistent
The value :consistent
asserts the following for identical input data (===
):
-
The way execution is completed (returning a value, calling an exception, or not completing execution) will always be the same.;
-
if the method returns control, the results will always be identical.
In particular, it follows that the method should not return a newly allocated mutable object. Mutable objects stored in different locations in memory are not identical, even if their contents are identical. |
The statement |
Однако для двух «возрастов мира» ``i`` и ``j``, таких что ``i ≠ j``, возможно, что ``fᵢ(x) ≢ fⱼ(y)``. Из этого далее следует, что возвращаемые значения функций `:consistent` не должны зависеть от состояния кучи или любого другого состояния, которое не является постоянным для данного «возраста мира».
The |
If the execution of the |
:effect_free
The value of :effect_free
asserts that the method is devoid of externally semantically visible side effects. Here is an incomplete list of such effects.:
-
changing the value of a global variable;
-
changing a heap (for example, an array or a mutable value), except in the cases specified below;
-
changing the method table (for example, by calling the eval function);
-
I/O operations (file, network, etc.);
-
switching tasks.
However, the following side effects are not clearly semantically visible, even if they can be observed:
-
memory allocation (for both mutable and immutable objects);
-
elapsed time;
-
garbage collection;
-
modification of objects in the heap whose lifetime does not exceed the execution time of the method (that is, they were placed in memory in the method and do not leave it);
-
returning a value (which is visible from the outside, but is not a side effect).
Simply put, an externally visible side effect is something that would affect the execution of the rest of the program if the function were not executed.
The statement |
:nothrow
The value :nothing
asserts that the execution of this method does not cause an exception (that is, the method either always returns a value or never returns control).
Exception handling can be used inside methods with the |
If executing a method can cause a |
:terminates_globally
The value :terminates_globally
asserts that the execution of this method eventually completes (with or without an error), that is, it does not go into an infinite loop.
The statement |
The compiler regards this statement as a clear sign that the execution of the method will be completed relatively quickly, and can (if allowed) call this method during compilation. Therefore, it is undesirable to provide this annotation to a method whose execution should be completed theoretically, but in practice this may not happen. |
:terminates_locally
The value of :terminates_locally
is similar to the value of :terminates_globally
, except that it applies to the syntactic execution order of only the annotated method. Thus, this is a much less strict (and therefore safer) statement that allows for the possibility of infinite execution if it is conditioned on another method being called.
The statement |
:notaskstate
The :notaskstate
parameter states that the method does not use or modify the state of the local task (task local storage, RNG state, etc.) and therefore can safely move between tasks without noticeable results.
The exception handling implementation uses the state stored in the task object. However, this state is currently not considered to be in the scope of |
The statement |
Accessing the task state usually also results in "polluting" other effects, such as |
:inaccessiblememonly
The :inaccessiblemonly
parameter states that the method does not access or modify externally accessible mutable memory. This means that a method can access or modify mutable memory for newly allocated objects that is unavailable to other methods or top-level execution before returning from the method, but it cannot access or modify any mutable global state or mutable memory that its arguments point to.
Here is an incomplete list of examples in which this assumption is incorrect: — a global reference or a call to |
The statement |
:noub
The :noub
parameter states that the method will not be executed in an indefinite manner (for any input data). Note that undefined behavior can technically lead to a violation of other side-effect statements by the method (for example, :consistent
or :effect_free
), however, this situation is not modeled and the absence of undefined behavior is assumed.
:nortcall
The :nortcall
parameter states that the method does not invoke Core.Compiler.return_type
and that any other methods that this method may call also do not call Core.Compiler.return_type
.
To be more precise, this statement can be used when calling |
:foldable
This value is a convenient shorthand for a set of side effects that must be guaranteed so that the compiler can perform the convolution of constants to be called at compile time. It is currently equivalent to the following values of setting
:
-
:consistent
-
:effect_free
-
:terminates_globally
-
:noub
-
:nortcall
The statement |
Explicit annotation of |
:removable
This value is a convenient shorthand for a set of side effects that must be guaranteed so that the compiler can remove a call whose result is not used at compile time. It is currently equivalent to the following values of setting
:
-
:effect_free
-
:nothrow
-
:terminates_globally
:total
This setting
value represents the most complete set of side effects. It is currently equivalent to the following values of setting
:
-
:consistent
-
:effect_free
-
:nothrow
-
:terminates_globally
-
:notaskstate
-
:inaccessiblememonly
-
:noub
-
:nortcall
|
Elimination of side effects
The names of side effects can be prefixed with !
. It means that the effect must be excluded from the previously defined meta-effect. For example, :total !:nothing
means that all statements apply to the call, but it may fail.
Managing withdrawal from use
#
Base.@deprecate
— Macro
@deprecate old new [export_old=true]
Removes the old
method from use, replacing it with a new
call, defining a new old
method with the specified signature in the process.
To prohibit the export of the old
method, set export_old
to false
.
See also the description Base.depwarn()
.
Compatibility: Julia 1.5
Since Julia 1.5, functions defined using the |
Examples
julia> @deprecate old(x) new(x)
old (generic function with 1 method)
julia> @deprecate old(x) new(x) false
old (generic function with 1 method)
Calls to the @deprecate
macro without explicit type annotations will define obsolete methods that accept any number of positional and named arguments of type Any
.
Compatibility: Julia 1.9
Named arguments are redirected if there is no explicit type annotation since Julia 1.9. In older versions, you can manually redirect positional and named arguments by calling |
To limit the output from using a specific signature, annotate the arguments of the old
method. 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 the old universal function from Main:
[1] old(x::Int64)
@ deprecated.jl:94
defines and disables the old(x' method.::Int)
, which is a mirror image of new(x::Int)
, but will not define or disable the old(x' method.::Float64)
.
#
Base.depwarn
— Function
Base.depwarn(msg::String, funcsym::Symbol; force=false)
Outputs the msg' message as a warning about decommissioning. The symbol `funcsym
must be the name of the calling function so that a warning about decommissioning is displayed only once for each call location. To ensure that the warning is always displayed, even if the Julia environment was started with --depwarn=no
(by default), set `force=true'.
See also the description @deprecate
.
Examples
function deprecated_func()
Base.depwarn("Don't use `deprecated_func()`!", :deprecated_func)
1 + 1
end
Missing values
#
Base.Missing
— Type
Missing
A type without fields, the only instance of which is — missing
— is used to represent missing values.
See also the description skipmissing
, nonmissingtype
, Nothing
.
#
Base.missing
— Constant
missing
The only instance of the type Missing
, representing the missing value.
See also the description NaN
, skipmissing
, nonmissingtype
.
#
Base.coalesce
— Function
coalesce(x...)
Returns the first of the argument values that is not equal to missing
, if any. Otherwise, it returns `missing'.
See also the description skipmissing
, something
and @coalesce
.
Examples
julia> coalesce(missing, 1)
1
julia> coalesce(1, missing)
1
julia> coalesce(nothing, 1) # возвращает `nothing`
julia> coalesce(missing, missing)
missing
#
Base.@coalesce
— Macro
@coalesce(x...)
Shortened version of the function coalesce
.
Examples
julia> f(x) = (println("f($x)"); missing);
julia> a = 1;
julia> a = @coalesce a f(2) f(3) error("`a` is still missing")
1
julia> b = missing;
julia> b = @coalesce b f(2) f(3) error("`b` is still missing")
f(2)
f(3)
ERROR: `b` is still missing
[...]
Compatibility: Julia 1.7
This macro was first implemented in Julia 1.7. |
#
Base.ismissing
— Function
ismissing(x)
Determines whether the argument x
has a value. missing
.
See also the description skipmissing
, isnothing
, isnan
.
#
Base.skipmissing
— Function
skipmissing(itr)
Returns an iterator over the elements of the itr
argument, skipping the values missing
. Access to the elements of the returned object is possible by the indexes of the object itr
, if it supports indexing. Indexes corresponding to missing values are not allowed.: they are skipped by functions keys
and eachindex
, and when trying to use them, a MissingException
occurs.
Use the method collect
to get an array (Array
) containing values other than missing' in `itr'. Please note: even if `itr' is a multidimensional array, the result will always be of type `Vector
, since it is impossible to delete missing values while preserving the dimensions of the input array.
Examples
julia> x = skipmissing([1, missing, 2])
skipmissing(Union{Missing, Int64}[1, missing, 2])
julia> sum(x)
3
julia> x[1]
1
julia> x[2]
ERROR: MissingException: the value at index (2,) is missing
[...]
julia> argmax(x)
3
julia> collect(keys(x))
2-element Vector{Int64}:
1
3
julia> collect(skipmissing([1, missing, 2]))
2-element Vector{Int64}:
1
2
julia> collect(skipmissing([1 missing; 2 missing]))
2-element Vector{Int64}:
1
2
#
Base.nonmissingtype
— Function
nonmissingtype(T::Type)
If T
is a type union that includes the type Missing
, it returns a new type without Missing
.
Examples
julia> nonmissingtype(Union{Int64,Missing})
Int64
julia> nonmissingtype(Any)
Any
Compatibility: Julia 1.3
This function has been exported since Julia 1.3. |
System
#
Base.run
— Function
run(command, args...; wait::Bool = true)
Executes a command object enclosed in reverse apostrophes (see the section on implementation of external programs, in the manual). It returns an error if any problems occur, including the termination of the process with a non-zero state (when the 'wait` argument is true).
The arguments are args...
allows you to pass file descriptors to the command in the same order as standard Unix file descriptors (for example, stdin, stdout, stderr, FD(3), FD(4)...
).
If the wait
argument is false, the process runs asynchronously. You can wait for it to finish and check its exit status by calling success
for the returned process object.
When the wait
argument is set to false, the I/O streams of the process are routed to devnull
. When the 'wait` argument is set to true, the I/O threads are shared with the parent process. To control I/O redirection, use the method pipeline
.
#
Base.devnull
— Constant
devnull
Used when redirecting streams: all data written to devnull is deleted. Equivalent to /dev/null
on Unix or NUL
on Windows. Using:
run(pipeline(`cat test.txt`, devnull))
#
Base.success
— Function
success(command)
Executes a command object enclosed in reverse apostrophes (see the section on execution of external programs, in the manual), and informs whether the execution was completed successfully (exit with code 0). If the process cannot be started, an exception occurs.
#
Base.process_running
— Function
process_running(p::Process)
Determines whether the process is currently running.
#
Base.process_exited
— Function
process_exited(p::Process)
Determines whether the process has completed.
#
Base.kill
— Method
kill(p::Process, signum=Base.SIGTERM)
Sends a signal to the process. By default, it terminates the process. Returns control successfully if the process has already ended, but returns an error if the process could not be completed for any reason (for example, due to a lack of necessary permissions).
#
Base.Sys.set_process_title
— Function
Sys.set_process_title(title::AbstractString)
Sets the process header. In some operating systems, this is an idle operation.
#
Base.Sys.get_process_title
— Function
Sys.get_process_title()
Returns the process header. On some systems, it always returns an empty string.
#
Base.ignorestatus
— Function
ignorestatus(command)
Marks the command object so that if its execution ends with a result code other than zero, an error does not occur.
#
Base.detach
— Function
detach(command)
Marks the command object so that it is executed in a new process group, so that it can continue to exist after the Julia process is completed and no CTRL+C interrupts are passed to it.
#
Base.Cmd
— Type
Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)
Cmd(exec::Vector{String})
Creates a 'Cmd` object representing an external program and its arguments from `cmd' specifying the values of optional named arguments:
-
ignorestatus::Bool
: If the value is set totrue
(default isfalse
), theCmd
object will not issue an error in case of a non-zero return code. -
detach::Bool
: if the value is set totrue' (default is `false'), the `Cmd
object will be executed in a new process group, so it can continue to exist after thejulia
process is completed and CTRL+C interrupts will not be passed to it. -
windows_verbatim::Bool
: if the value is set totrue' (default is `false'), then in Windows, the `Cmd
object will send the command line to the process without enclosing the arguments in quotation marks or escaping them, even if the arguments contain spaces. (In Windows, arguments are passed to the program as a single command line, and the program itself is responsible for analyzing the arguments. By default, empty arguments and arguments with spaces or tabs on the command line are enclosed in double quotes ("
), and backslashes are placed before the characters\
and"
. Thewindows_verbatim=true
argument is useful for running programs that analyze the command line in a non-standard way.) It is valid only in the Windows operating system. -
windows_hide::Bool
: if the value is set totrue' (default is `false
), then in Windows the new console window is not displayed when executing theCmd
object. It does not work if the console is already open, or on systems other than Windows. -
'env`: Specifies the environment variables used when executing the
Cmd
object. 'env` is either a dictionary with string keys and values, or an array of strings in the form"var=val"
, or an array or tuple of pairs"var"=>val
. To change (rather than replace) an existing environment, initializeenv
withcopy(ENV)
, and then setenv["var"]=val
as needed. To add a new block to the environment of theCmd
object without replacing all the elements, use the functionaddenv()
. It returns theCmd
object with the updated environment. -
dir::AbstractString
: specifies the working directory for the command (instead of the current directory).
If no named arguments are specified, the current values from `cmd' are used.
Note that the constructor is Cmd(exec)
does not create a copy of exec'. All subsequent `exec
changes will be reflected in the Cmd
object.
The most common way to construct a Cmd
object is using command literals (reverse apostrophes), for example:
`ls -l`
Then the object can be passed to the Cmd
constructor to change the parameters, for example:
Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)
#
Base.setenv
— Function
setenv(command::Cmd, env; dir)
Specifies the environment variables used when executing the specified command'. 'env
is either a dictionary with string keys and values, or an array of strings in the form of "var=val"
, or zero or several arguments in the form of pairs of "var"=>val
. To change (rather than replace) an existing environment, create an env
using copy(ENV)
, and then set env["var"]=val
as needed, or use the function addenv
.
Using the named dir
argument, you can specify the working directory for the command. By default, the dir
argument is equal to the current set value of dir
for command
(that is, the current working directory, if this value has not been redefined).
#
Base.addenv
— Function
addenv(command::Cmd, env...; inherit::Bool = true)
Merges new environment variables with the environment of the specified object Cmd
, returning a new Cmd
object. If the keys are repeated, the corresponding variables are replaced. If the values of the environment variables have not yet been set in the object passed in the command
argument, when calling the addenv()
function, the current environment is inherited, provided that the inherit
argument is set to true
. Keys with the value nothing
are deleted from env.
Compatibility: Julia 1.6
This feature requires a Julia version of at least 1.6. |
#
Base.withenv
— Function
withenv(f, kv::Pair...)
Executes the function f
in an environment that has been temporarily modified (and not replaced, as when using setenv
) using one or more arguments kv
in the form of pairs "var"=>val
. The withenv
function is usually used with the syntax withenv(kv...) do ... end
. Using the nothing
value, you can temporarily disable the environment variable (if it is set). When the withenv function returns control, the original environment is restored.
Changing the environment is not a thread-safe operation. To execute external commands with another environment from the parent process, it is better to use 'addenv`, not `withenv'. |
#
Base.setcpuaffinity
— Function
setcpuaffinity(original_command::Cmd, cpus) -> command::Cmd
Sets the CPU binding for the command
command as a list of CPU IDs cpus' (starting from 1). Passing the value `cpus = nothing
cancels the CPU binding if it was configured for the 'original_command` command.
This feature is only supported on Linux and Windows. It is not supported on macOS because the libuv library does not support the binding configuration.
Compatibility: Julia 1.8
This feature requires a Julia version of at least 1.8. |
Examples
On Linux, you can see how the setcpuaffinity function works using the taskset command line program.
julia> run(setcpuaffinity(`sh -c 'taskset -p $$'`, [1, 2, 5]));
pid 2273's current affinity mask: 13
Please note: the mask value 13
means that the first, second, and fifth bits are enabled (if you count from the lowest bit):
julia> 0b010011
0x13
#
Base.pipeline
— Method
pipeline(from, to, ...)
Creates a pipeline from the data source to the destination object. The source and destination object can be commands, input/output streams, strings, or the results of other calls to the pipeline method. At least one argument must be a command. Strings are file names. If there are more than two arguments, they are concatenated from left to right. For example, pipeline(a,b,c)
is equivalent to `pipeline(pipeline(a,b),c)'. This allows you to define multi-stage pipelines more concisely.
Examples:
run(pipeline(`ls`, `grep xyz`))
run(pipeline(`ls`, "out.txt"))
run(pipeline("out.txt", `grep xyz`))
#
Base.pipeline
— Method
pipeline(command; stdin, stdout, stderr, append=false)
Redirects I/O to or from the specified command'. Named arguments define the command streams that should be redirected. The 'append
argument determines whether the output data is added to the file. This is a more general version of the pipeline
function with two arguments. Calling pipeline(from, to)
is equivalent to calling pipeline(from, stdout=to)
when from
is a command, or calling pipeline(to, stdin=from)
when from
is a different type of data source.
Examples:
run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt"))
run(pipeline(`update`, stdout="log.txt", append=true))
#
Base.Libc.gethostname
— Function
gethostname() -> String
Returns the hostname of the local computer.
#
Base.Libc.getpid
— Function
getpid() -> Int32
Returns the ID of the Julia process.
getpid(process) -> Int32
Returns the ID of the child process, if it still exists.
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
#
Base.Libc.time
— Method
time() -> Float64
Returns the system time in seconds from the beginning of the Unix time countdown with a fairly high accuracy (usually at the microsecond level).
#
Base.time_ns
— Function
time_ns() -> UInt64
Returns the time in nanoseconds. The time corresponding to the value 0 is not defined. The countdown starts anew every 5.8 years.
#
Base.@time
— Macro
@time expr
@time "description" expr
A macro that executes an expression and outputs the time spent on execution, the number of objects allocated in memory, and the total number of bytes allocated during execution, after which it returns the value of the expression. The time spent on garbage collection, compiling new code, or recompiling invalid code is shown as a percentage. The number of lock conflicts that delayed execution is also displayed. ReentrantLock
.
If necessary, you can specify a description string that will be displayed before the time spent report.
The system can check the contents of the expression @time
and compile the called code before starting execution of the top-level expression. In this case, some of the time spent on compilation is not taken into account. To account for this time, you can run @time @eval ...
.
See also the description @showtime
, @timev
, @timed
, @elapsed
, @allocated
and @allocations
.
For more thorough performance testing, you can use the macro `@btime' from the Benchmark Tools package.jl, which, among other things, evaluates the function several times to reduce the influence of random factors. |
Compatibility: Julia 1.8
The ability to add a description appeared in version Julia 1.8. |
The recompilation time has been displayed separately from the compilation time since Julia 1.8.
Compatibility: Julia 1.11
Notification of blocking conflicts appeared 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)
2
julia> @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)
end
1: 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
It acts in the same way as the macro @time
, but also outputs the analyzed expression for reference.
Compatibility: Julia 1.8
This macro was added in version Julia 1.8. |
See also the description @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 detailed version of the macro @time'. First, it outputs the same information as `@time
, then all non-zero memory allocation counters, and then returns the value of the expression.
If necessary, you can specify a description string that will be displayed before the time spent report.
Compatibility: Julia 1.8
The ability to add a description appeared in version Julia 1.8. |
See also the description @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): 546769547
gc time (ns): 23115606
bytes allocated: 122297811
pool allocs: 2197930
non-pool GC allocs:1327
malloc() calls: 36
realloc() calls: 5
GC pauses: 3
julia> @timev x * x;
0.000010 seconds (1 allocation: 896 bytes)
elapsed time (ns): 9848
bytes allocated: 896
pool allocs: 1
#
Base.@timed
— Macro
@timed
The macro that executes the expression and returns its value, the elapsed time in seconds, the total amount of allocated memory in bytes, the duration of garbage collection, an object with different memory allocation counters, compilation time in seconds and recompilation time in seconds. The number of lock conflicts that delayed execution is also displayed. ReentrantLock
.
The system can check the contents of the @timed
expression and compile the called code before starting execution of the top-level expression. In this case, part of the time spent on compilation is not taken into account. To account for this time, you can run @timed @eval ...
.
See also the description @time
, @timev
, @elapsed
, @allocated
, @allocations
and @lock_conflicts
.
julia> stats = @timed rand(10^6);
julia> stats.time
0.006634834
julia> stats.bytes
8000256
julia> stats.gctime
0.0055765
julia> propertynames(stats.gcstats)
(:allocd, :malloc, :realloc, :poolalloc, :bigalloc, :freecall, :total_time, :pause, :full_sweep)
julia> stats.gcstats.total_time
5576500
julia> stats.compile_time
0.0
julia> stats.recompile_time
0.0
Compatibility: Julia 1.5
In Julia 1.5, the type of value returned by this macro has changed from |
Compatibility: Julia 1.11
The fields |
#
Base.@elapsed
— Macro
@elapsed
A macro that evaluates an expression, but instead returns the number of seconds spent on execution as a floating-point number.
The system can check the contents of the @elapsed
expression and compile the called code before starting execution of the top-level expression. In this case, part of the time spent on compilation is not taken into account. To account for this time, you can run @elapsed @eval ...
.
See also the description @time
, @timev
, @timed
, @allocated
and @allocations
.
julia> @elapsed sleep(0.3)
0.301391426
#
Base.@allocations
— Macro
@allocations
A macro that evaluates an expression, but returns the total number of selections during the calculation instead of the result.
See also the description @allocated
, @time
, @timev
, @timed
and @elapsed
.
julia> @allocations rand(10^6)
2
Compatibility: Julia 1.9
This macro was added in version Julia 1.9. |
#
Base.@lock_conflicts
— Macro
@lock_conflicts
A macro that evaluates an expression, but instead of the result returns the total number of lock conflicts during the calculation, i.e. situations where a lock attempt is made 'ReentrantLock` resulted in a wait because the lock had already been set.
julia> @lock_conflicts begin
l = ReentrantLock()
Threads.@threads for i in 1:Threads.nthreads()
lock(l) do
sleep(1)
end
end
end
5
Compatibility: Julia 1.11
This macro was added in version Julia 1.11. |
#
Base.EnvDict
— Type
EnvDict() -> EnvDict
The only instance of this type provides an interface in the form of a hash table for accessing environment variables.
#
Base.ENV
— Constant
ENV
A reference to the EnvDict type with a single instance that provides an interface in the form of a dictionary for accessing system environment variables.
(On Windows, the system environment variables are case-insensitive, so 'ENV` converts all keys to uppercase for display, iteration, and copying. In portable code, variables should not differ in case; keep in mind that, despite writing the variable name in lowercase letters, the corresponding key in ENV
may be written in uppercase letters.)
Changing the environment is not a thread-safe operation. |
Examples
julia> ENV
Base.EnvDict with "50" entries:
"SECURITYSESSIONID" => "123"
"USER" => "username"
"MallocNanoZone" => "0"
⋮ => ⋮
julia> ENV["JULIA_EDITOR"] = "vim"
"vim"
julia> ENV["JULIA_EDITOR"]
"vim"
#
Base.Sys.STDLIB
— Constant
Sys.STDLIB::String
A string that contains the full path to the directory containing the stdlib
packages.
#
Base.Sys.isunix
— Function
Sys.isunix([os])
A predicate for checking whether the OS provides a Unix-like interface. See the documentation section Operating system processing.
#
Base.Sys.isapple
— Function
Sys.isapple([os])
A predicate for checking whether an OS is derived from Apple Macintosh OS X or Darwin. See the documentation section Operating system processing.
#
Base.Sys.islinux
— Function
Sys.islinux([os])
A predicate for checking whether an OS is derived from Linux. See the documentation section Operating system processing.
#
Base.Sys.isbsd
— Function
Sys.isbsd([os])
A predicate for checking whether the OS is derived from BSD. See the documentation section Operating system processing.
The Darwin kernel is derived from BSD, so the function |
#
Base.Sys.isfreebsd
— Function
Sys.isfreebsd([os])
A predicate for checking whether the OS is derived from FreeBSD. See the documentation section Operating system processing.
Not to be confused with the function |
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
#
Base.Sys.isopenbsd
— Function
Sys.isopenbsd([os])
A predicate for checking whether the OS is derived from OpenBSD. See the documentation section Operating system processing.
Not to be confused with the function |
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
#
Base.Sys.isnetbsd
— Function
Sys.isnetbsd([os])
A predicate for checking whether the OS is derived from NetBSD. See the documentation section Operating system processing.
Not to be confused with the function |
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
#
Base.Sys.isdragonfly
— Function
Sys.isdragonfly([os])
A predicate for checking whether the OS is derived from DragonFly BSD. See the documentation section Operating system processing.
Not to be confused with the function |
Compatibility: Julia 1.1
This feature requires a Julia version of at least 1.1. |
#
Base.Sys.iswindows
— Function
Sys.iswindows([os])
A predicate for checking whether the OS is derived from Microsoft Windows NT. See the documentation section Operating system processing.
#
Base.Sys.windows_version
— Function
Sys.windows_version()
Returns the Windows NT kernel version number as a value of type VersionNumber', i.e. `v"major.minor.build"
or, if the function is not running on Windows, v"0.0.0"
.
#
Base.Sys.total_memory
— Function
Sys.total_memory()
Returns the total amount of RAM (including the currently occupied one) in bytes. This volume may be limited, for example, to Linux control groups. To get unlimited volume, use the function `Sys.total_physical_memory()'.
#
Base.Sys.free_physical_memory
— Function
Sys.free_physical_memory()
Returns the amount of free system memory in bytes. The current process may not have the full amount available; to get the actual amount of available memory, use the Sys' function.free_memory()
.
#
Base.Sys.total_physical_memory
— Function
Sys.total_physical_memory()
Returns the total amount of RAM (including the currently occupied one) in bytes. The current process may not have access to the entire volume; see the description of the function `Sys.total_memory()'.
#
Base.Sys.isjsvm
— Function
Sys.isjsvm([os])
A predicate for checking whether the Julia environment is running on a JavaScript virtual machine (JSVM), including, for example, embedding WebAssembly JavaScript in a web browser.
Compatibility: Julia 1.2
This feature requires a Julia version of at least 1.2. |
#
Base.Sys.loadavg
— Function
Sys.loadavg()
Returns the average load value. See https://en.wikipedia.org/wiki/Load_ (computing).
#
Base.Sys.isexecutable
— Function
isexecutable(path::String)
Returns true
if the specified path
has executable file permissions.
This permission may change before the user executes the |
Prior to Julia 1.6, the Windows file system ACL was queried incorrectly, so the value |
See also the description ispath
, isreadable
and iswritable
.
#
Base.Sys.isreadable
— Function
isreadable(path::String)
Returns the value true
if, according to the access permissions for this path
object, the current user can read from it.
This permission may change before the user calls |
Currently, this function incorrectly polls the Windows file system ACL, so it may return incorrect results. |
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description ispath
, isexecutable
and iswritable
.
isreadable(io) -> Bool
Returns false
if reading from the specified I/O object is not supported.
Examples
julia> open("myfile.txt", "w") do io
print(io, "Hello world!");
isreadable(io)
end
false
julia> open("myfile.txt", "r") do io
isreadable(io)
end
true
julia> rm("myfile.txt")
#
Base.Sys.iswritable
— Function
iswritable(path::String)
Returns the value true
if, according to the access permissions for this path
object, the current user can write to it.
This permission may change before the user calls |
Currently, this function incorrectly polls the Windows file system ACL, so it may return incorrect results. |
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description ispath
, isexecutable
and isreadable
.
iswritable(io) -> Bool
Returns false
if writing to the specified I/O object is not supported.
Examples
julia> open("myfile.txt", "w") do io
print(io, "Hello world!");
iswritable(io)
end
true
julia> open("myfile.txt", "r") do io
iswritable(io)
end
false
julia> rm("myfile.txt")
#
Base.Sys.username
— Function
Sys.username() -> String
Returns the name of the current user. If the user’s name cannot be determined or it is empty, this function returns an error.
To get a username that can be redefined using an environment variable, such as USER
, it is recommended to use
user = get(Sys.username, ENV, "USER")
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description homedir
.
#
Base.@static
— Macro
@static
Partially evaluates the expression during analysis.
For example, @static Sys.iswindows() ? foo :bar
evaluates the function Sys.iswindows()
and inserts foo
or bar' into the expression. This is useful in cases where the construct is invalid on other platforms, such as when calling a non-existent function `ccall
. The following syntax options are also acceptable: @static if Sys.isapple() foo end
and @static foo <&&,||> bar
.
Version control
#
Base.VersionNumber
— Type
VersionNumber
The type of version number corresponding to the specifications https://semver.org /[semantic versioning (semver)]. The value consists of the primary and secondary version numbers, as well as the patch number, followed by alphanumeric pre-release and build designations.
VersionNumber
objects can be compared using any standard comparison operators. (==
, <
, <=
and so on) according to the rules of semver.
The VersionNumber
has 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 the description of the macro @v_str
, which allows you to efficiently create VersionNumber
objects based on literal strings in semver format, a description of the constant VERSION
, containing the VersionNumber
value of the Julia version used, as well as a section of the manual dedicated to numeric version literals.
Examples
julia> a = VersionNumber(1, 2, 3)
v"1.2.3"
julia> a >= v"1.2"
true
julia> b = VersionNumber("2.0.1-rc1")
v"2.0.1-rc1"
julia> b >= v"2.0.1"
false
#
Base.@v_str
— Macro
@v_str
A string macro that is used to analyze a string and convert it to VersionNumber
.
Examples
julia> v"1.2.3"
v"1.2.3"
julia> v"2.0.1-rc1"
v"2.0.1-rc1"
Mistakes
#
Base.error
— Function
error(message::AbstractString)
Raises an ErrorException
with the specified message.
error(msg...)
Raises an 'ErrorException` with a message created using string(msg…)+
.
#
Base.rethrow
— Function
rethrow()
Re-invokes the current exception from the catch
block. A re-raised exception will be passed on as if it had not been caught.
The alternative form |
#
Base.backtrace
— Function
backtrace()
Returns a backtracking object for the current program point.
#
Base.catch_backtrace
— Function
catch_backtrace()
Returns a backtrace of the current exception for use in 'catch` blocks.
#
Base.current_exceptions
— Function
current_exceptions(task::Task=current_task(); [backtrace::Bool=true])
Returns the stack of exceptions currently being handled. In the case of nested catch blocks, there may be several current exceptions. The last exception thrown will be the last one on the stack. The stack is returned as an object ExceptionStack
— an abstract vector of named tuples (exception,backtrace)
. If the backtrace
argument is false, the backtrace in each pair will be `nothing'.
When passing the task
argument, the stack of current exceptions for an arbitrary task is explicitly returned. This is useful for checking for tasks that could not be completed due to uncaught exceptions.
Compatibility: Julia 1.7
In versions Julia 1.1—1.6, this function was experimental, called `catch_stack()' and returned a simple vector of tuples. |
#
Base.@assert
— Macro
@assert cond [text]
Causes an error AssertionError
, if the condition cond
is false'. This is the preferred syntax for writing statements that represent conditions that are considered true, but which the user can nevertheless check for debugging purposes. If the approval is not met, an optional `text
message is displayed.
Assertions can be disabled at some optimization levels. Therefore, they should only be used for debugging purposes. Do not use assertions to verify authenticity (such as passwords) or array boundaries. The correct behavior of a function in code should not be based on the side effects of executing |
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
— Function
Experimental.register_error_hint(handler, exceptiontype)
Registers the hint function handler(io, exception)
, which can suggest possible ways for users to work around errors. The handler
function should check whether the 'exception` meets the conditions for issuing a prompt, and, if so, send the output to io
. In packages, the function register_error_hint
must be called from the function `__init__'.
For certain types of exceptions, the handler function must accept additional arguments.
-
MethodError
: specifyhandler(io, exc::MethodError, argtypes, kwargs)
to separate arguments into positional and named ones.
The hint text should usually start with \n
.
When defining custom exception types, the showerror
method can support hints by calling Base.Experimental.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 # Цвет необязателен, просто демонстрируется такая возможность. print(io, "\nDid you mean to call ") printstyled(io, "`any_number`?", color=:cyan) end end end end
If you now call Hinter.only_int
for an object of a non-Int type (which will result in a MethodError
error), a prompt will be displayed:
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: ...
Compatibility: Julia 1.5
Hints for user errors are available starting with Julia 1.5. |
This is an experimental interface. It can be changed or deleted without notice. To insure against changes, it is advisable to place all registrations inside the |
#
Base.Experimental.show_error_hints
— Function
Experimental.show_error_hints(io, ex, args...)
Calls all handlers from Base.Experimental.register_error_hint
for a specific type of exception, typeof(ex)
. The args
must contain all the other arguments that the handler expects for this type.
Compatibility: Julia 1.5
Hints for user errors are available starting with Julia 1.5. |
This is an experimental interface. It can be changed or deleted without notice. |
#
Core.ArgumentError
— Type
ArgumentError(msg)
Invalid arguments are passed to the function. `msg' — error description message.
#
Core.AssertionError
— Type
AssertionError([msg])
The approval condition is not `true'. The optional argument `msg' is a string describing the error.
Examples
julia> @assert false "this is not true"
ERROR: AssertionError: this is not true
The AssertionError
error is usually caused by a macro @assert
.
#
Core.BoundsError
— Type
BoundsError([a],[i])
When accessing the array a
by index, an attempt was made to access the out-of-bounds element by index i
.
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
— Type
CompositeException
A wrapper for a vector of exceptions caused by an object Task
(for example, created by a remote workflow connected via a channel, a local asynchronous write operation, or a remote workflow managed by `pmap'). Contains information about a series of exceptions. For example, if a group of workflows performs a number of tasks and several of these processes fail, the "CompositeException" object will contain a "package" of information about where and why exceptions occurred from each workflow.
#
Base.DimensionMismatch
— Type
DimensionMismatch([msg])
The called objects have a different dimension. The optional argument `msg' is a string describing the error.
#
Core.DivideError
— Type
DivideError()
An attempt has been made to perform integer division with zero in the denominator.
Examples
julia> 2/0
Inf
julia> div(2, 0)
ERROR: DivideError: integer division error
Stacktrace:
[...]
#
Core.DomainError
— Type
DomainError(val)
DomainError(val, msg)
The val
argument of a function or constructor is outside the scope of the definition.
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:
[...]
#
Core.ErrorException
— Type
ErrorException(msg)
A universal type of error. The error message in the .msg
field may contain clarifying information.
Examples
julia> ex = ErrorException("I've done a bad thing");
julia> ex.msg
"I've done a bad thing"
#
Core.InexactError
— Type
InexactError(name::Symbol, T, val)
It is not possible to accurately convert the value of val
to the type T
in the method of the name
function.
Examples
julia> convert(Float64, 1+2im)
ERROR: InexactError: Float64(1 + 2im)
Stacktrace:
[...]
#
Core.InterruptException
— Type
InterruptException()
The process was stopped as a result of an interrupt from the terminal (CTRL+C).
Note that in the Julia script, which is run without the '-i` parameter (interactive session), the 'InterruptException` exception is not called by default. Challenge Base.exit_on_sigint(false)
in the script, it can restore the behavior of the REPL. The Julia script can also be run using the command
julia -e "include(popfirst!(ARGS))" script.jl
so that interrupting CTRL+C during execution causes the 'InterruptException` exception.
#
Base.KeyError
— Type
KeyError(key)
When accessing an object of type AbstractDict
(Dict
) or Set
by index, an attempt was made to access or delete a non-existent element.
#
Core.LoadError
— Type
LoadError(file::AbstractString, line::Int, error)
When trying to apply the function include
, require
or using
an error has occurred on the file. Detailed information about the error should be available in the .error
field.
Compatibility: Julia 1.7
As of Julia 1.7, macros |
#
Core.MethodError
— Type
MethodError(f, args)
The specified universal function does not have a method with the required type signature. Or there is no unique, most specific method.
#
Core.OutOfMemoryError
— Type
OutOfMemoryError()
The operation allocated too much memory for processing by the system or the garbage collector.
#
Core.ReadOnlyMemoryError
— Type
ReadOnlyMemoryError()
The operation attempted to write to read-only memory.
#
Core.OverflowError
— Type
OverflowError(msg)
The result of the expression is too large for the specified type and will result in cyclic hyphenation.
#
Base.ProcessFailedException
— Type
ProcessFailedException
Indicates the exit status of the process, indicating a problem. When executing commands or pipelines, this exception indicates the return of a non-zero exit code (that is, the triggered process has failed).
#
Core.StackOverflowError
— Type
StackOverflowError()
The size of the function call has exceeded the size of the call stack. The reason is usually the infinite recursion of the call.
#
Base.SystemError
— Type
SystemError(prefix::AbstractString, [errno::Int32])
The system call ended with an error code (in the global variable errno
).
#
Core.TypeError
— Type
TypeError(func::Symbol, context::AbstractString, expected::Type, got)
Type approval failed or a built-in function call with an incorrect argument type.
#
Core.UndefKeywordError
— Type
UndefKeywordError(var::Symbol)
The required named argument var
is not specified in the function call.
Examples
julia> function my_func(;my_arg)
return my_arg + 1
end
my_func (generic function with 1 method)
julia> my_func()
ERROR: UndefKeywordError: keyword argument `my_arg` not assigned
Stacktrace:
[1] my_func() at ./REPL[1]:2
[2] top-level scope at REPL[2]:1
#
Core.UndefRefError
— Type
UndefRefError()
The element or field is not defined for the specified object.
Examples
julia> struct MyType
a::Vector{Int}
MyType() = new()
end
julia> A = MyType()
MyType(#undef)
julia> A.a
ERROR: UndefRefError: access to undefined reference
Stacktrace:
[...]
#
Core.UndefVarError
— Type
UndefVarError(var::Symbol, [scope])
The symbol is not defined in the current area.
Examples
julia> a
ERROR: UndefVarError: `a` not defined in `Main`
julia> a = 1;
julia> a
1
#
Base.StringIndexError
— Type
StringIndexError(str, i)
An error occurred due to an attempt to access the string str
at an invalid index `i'.
#
Core.InitError
— Type
InitError(mod::Symbol, error)
An error occurred when executing the __init__
function of the module. The error caused is available in the .error
field.
#
Base.retry
— Function
retry(f; delays=ExponentialBackOff(), check=nothing) -> Function
Returns an anonymous function that calls the function f
. If an exception occurs, the function f
is called again each time check
returns the value 'true', after a pause, the duration of which is specified in seconds in the delays
argument. The current state of delays
and the Exception
object should be passed to check
.
Compatibility: Julia 1.2
Prior to Julia 1.2, this function had a limited signature `f::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
— Type
ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)
An iterator of the type Float64
of length n', the elements of which increase exponentially at a rate in the range `factor
* (1 ± jitter
). The first element is `first_delay'; the maximum size of the elements is `max_delay'.
Events
#
Base.Timer
— Method
Timer(callback::Function, delay; interval = 0)
Creates a timer, each time it is triggered, the `callback' function is executed.
Pending tasks are activated, and the callback
function is first called after a delay of delay
seconds, and then called again with an interval of interval
seconds. If the interval
argument is 0', the callback is executed only once. The 'callback
function is called with one argument — the timer itself. To stop the timer, call the close
function. If the timer has finished counting down, the callback
function can be executed one last time.
Examples
In this case, the first number is displayed after a two-second pause, and the following numbers are displayed with a slight delay.
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)
end
1
2
3
#
Base.Timer
— Type
Timer(delay; interval = 0)
Creates a timer that activates tasks waiting for it to be triggered (by calling the function wait
for the timer object).
Pending tasks are activated after an initial delay of at least delay
seconds, and then executed repeatedly with an interval of at least interval
seconds. If the interval
argument is '0', the timer is triggered only once. When the timer closes (using the function close
), pending tasks are activated with an error. To check if the timer is still active, use the function isopen
.
The interval may gradually shift due to the accumulation of delays. If you want events to occur at certain absolute points in time, create a new timer after the previous one ends, calculating the difference to the next point in time. |
Exit points are required to update the state of the Timer object. For example, |
#
Base.AsyncCondition
— Type
AsyncCondition()
Creates an asynchronous condition that activates tasks waiting for it to be triggered (by calling the function wait
for the object), when receiving a message from C by calling uv_async_send'. When the object is closed (using the function `close
), pending tasks are activated with an error. To check if the object is still active, use the function isopen
.
This allows for an implicit ordering of memory during receipt and release between sending and waiting threads.
#
Base.AsyncCondition
— Method
AsyncCondition(callback::Function)
Creates an asynchronous condition that calls the specified 'callback` function. The 'callback` function is passed one argument, the asynchronous condition object itself.
Display
#
Base.parentmodule
— Function
parentmodule(m::Module) -> Module
Returns the `Module' containing this module. Its own parent module is `Main'.
See also the description names
, nameof
, fullname
, @__MODULE__
.
Examples
julia> parentmodule(Main)
Main
julia> parentmodule(Base.Broadcast)
Base
parentmodule(t::DataType) -> Module
Defines a module that contains a definition of the DataType
type (possibly encapsulated in `unionAll').
Examples
julia> module Foo
struct Int end
end
Foo
julia> parentmodule(Int)
Core
julia> parentmodule(Foo.Int)
Foo
parentmodule(f::Function) -> Module
Defines a module that contains the (first) definition of a universal function.
parentmodule(f::Function, types) -> Module
Defines the module that contains the first method of the universal function f
, corresponding to the specified types of types
.
parentmodule(m::Method) -> Module
Returns the module in which the specified method m
is defined.
Compatibility: Julia 1.9
To pass |
#
Base.pathof
— Method
pathof(m::Module)
Returns the path to the m.jl
file from which the m
module was imported, or the value nothing
if the m
module was not imported from the package.
Use the function dirname
to get the directory name from the path and the function basename
to get the file name.
See also the description pkgdir
.
#
Base.pkgdir
— Method
pkgdir(m::Module[, paths::String...])
Returns the root directory of the package in which the module m
is declared, or the value nothing
if the module m
is not declared in the package. If necessary, you can specify the path components that make up the path inside the package’s root directory.
To get the root directory of the package in which the current module is implemented, you can use the form pkgdir(@__MODULE__)
.
If an extension module is specified, the root directory 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 also the description pathof
.
Compatibility: Julia 1.7
To use the optional |
#
Base.pkgversion
— Method
pkgversion(m::Module)
Returns the version of the package from which the module m
was imported, or the value nothing
if the module m
was not imported from the package or imported from the package without a value in the version field.
The version is read from the package’s Project.toml file during package download.
To get the version of the package from which the module was imported, you can use the form pkgversion(@__MODULE__)
.
Compatibility: Julia 1.9
This feature appeared in version Julia 1.9. |
#
Base.moduleroot
— Function
moduleroot(m::Module) -> Module
Finds the root module of the specified module. This is the first module in the chain of parent modules m
, which can be a registered root module or its own parent module.
#
__module__
— Keyword
__module__
The __module__' argument is available only inside the macro and provides information (in the form of a `Module
object) about the context of the macro call extension. For more information, see the section of the manual on calling macros.
#
__source__
— Keyword
__source__
The __source__' argument is available only inside the macro and provides information (in the form of a `LineNumberNode
object) about the location of the analyzer for the '@` character in the macro call. For more information, see the section of the manual on calling macros.
#
Base.@__MODULE__
— Macro
@__MODULE__ -> Module
Returns the module Module
that the top-level eval call is associated with, that is, the Module
from which the code is currently being read.
#
Base.@__FILE__
— Macro
@__FILE__ -> String
Expands to a string with the path to the file that contains the macro call, or to an empty string when calculated using julia -e <expr>
. If there is no information about the analyzer source code, it returns the value nothing'. See also the description of the constant `PROGRAM_FILE
.
#
Base.@__DIR__
— Macro
@__DIR__ -> String
A macro for getting the absolute path to the current directory as a string.
In the script, returns the directory of the script containing the macro call @__DIR__'. When running from REPL or calculating using `julia -e <expr>
, it returns the current working directory.
Examples
The difference in the behavior of @__DIR__+
and pwd()
can be illustrated by creating a simple script in a directory other than the current working directory and executing both commands.:
julia> cd("/home/JuliaUser") # рабочий каталог
julia> # создаем скрипт по пути /home/JuliaUser/Projects
open("/home/JuliaUser/Projects/test.jl","w") do io
print(io, """
println("@__DIR__ = ", @__DIR__)
println("pwd() = ", pwd())
""")
end
julia> # выводит каталог скрипта и текущий рабочий каталог
include("/home/JuliaUser/Projects/test.jl")
@__DIR__ = /home/JuliaUser/Projects
pwd() = /home/JuliaUser
#
Base.@__LINE__
— Macro
@__LINE__ -> Int
Expands to the number of the line in which the macro is called. If the row number could not be determined, it returns the value `0'.
#
Base.fullname
— Function
fullname(m::Module)
Returns the full name of the module as a tuple of characters. For example:
Examples
julia> fullname(Base.Iterators)
(:Base, :Iterators)
julia> fullname(Main)
(:Main,)
#
Base.names
— Function
names(x::Module; all::Bool = false, imported::Bool = false)
Returns the vector of public names Module', excluding obsolete names. If the `all
argument is true, the list also includes non-public names defined in the module, obsolete names, and names generated by the compiler. If the imported
argument is true, names that are explicitly exported from other modules are also included. The names are returned in sorted order.
The names defined in the 'Main` module are a special case: they are all considered public, since names from Main
are not explicitly marked as public in Julia.
From |
See also the description Base.isexported
, Base.ispublic
, Base.@locals
, @__MODULE__
.
#
Base.isexported
— Function
isexported(m::Module, s::Symbol) -> Bool
Determines whether the symbol has been exported from the module.
julia> module Mod
export foo
public bar
end
Mod
julia> Base.isexported(Mod, :foo)
true
julia> Base.isexported(Mod, :bar)
false
julia> Base.isexported(Mod, :baz)
false
#
Base.ispublic
— Function
ispublic(m::Module, s::Symbol) -> Bool
Determines whether the symbol is marked as public in the module.
Exported symbols are considered publicly available.
Compatibility: Julia 1.11
This feature and the concept of accessibility appeared in Julia 1.11. |
See also the description isexported
, names
julia> module Mod
export foo
public bar
end
Mod
julia> Base.ispublic(Mod, :foo)
true
julia> Base.ispublic(Mod, :bar)
true
julia> Base.ispublic(Mod, :baz)
false
#
Base.nameof
— Method
nameof(f::Function) -> Symbol
Returns the name of the universal function Function
as a character. For anonymous functions, this name is generated by the compiler. For explicitly declared subtypes, `Function' is the name of the function type.
#
Base.functionloc
— Method
functionloc(f::Function, types)
Returns the tuple (filename,line)
with the location of the definition of the universal function `Function'.
#
Base.functionloc
— Method
functionloc(m::Method)
Returns the tuple (filename,line)
with the location of the method definition `Method'.
#
Base.@locals
— Macro
@locals()
Creates a dictionary that contains the names (in the form of symbols) and the values of all local variables defined starting from the place of the call.
Compatibility: Julia 1.1
This macro requires a Julia version of at least 1.1. |
Examples
julia> let x = 1, y = 2
Base.@locals
end
Dict{Symbol, Any} with 2 entries:
:y => 2
:x => 1
julia> 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
— Function
getglobal(module::Module, name::Symbol, [order::Symbol=:monotonic])
Gets the value of the name
binding from the `module'. If necessary, atomic ordering can be specified for this operation, otherwise monotonic ordering will be used by default.
Although access to module bindings using 'getfield` is still supported for compatibility, getglobal
should always be preferred, since getglobal
allows you to control atomic ordering (getfield
is always monotonic) and better indicates the purpose of the code for both the user and the compiler.
Most users should not call this function directly. In all cases, except very specific ones, you should use the function getproperty
or the appropriate syntax (i.e. `module.name `).
Compatibility: Julia 1.9
This feature requires a Julia version of at least 1.9. |
See also the description getproperty
and setglobal!
.
Examples
julia> a = 1
1
julia> module M
a = 2
end;
julia> getglobal(@__MODULE__, :a)
1
julia> getglobal(M, :a)
2
#
Core.setglobal!
— Function
setglobal!(module::Module, name::Symbol, x, [order::Symbol=:monotonic])
Sets or changes the value of the name (name') of the binding in the module to `x
. Type conversion is not performed, so if the type has already been declared for binding, x
must have the appropriate type, otherwise an error will occur.
In addition, atomic ordering can be specified for this operation, otherwise monotonic ordering will be used by default.
Users usually access this functionality using the function setproperty!
or the appropriate syntax (i.e. module.name = x
), so it is intended only for very specific use cases.
Compatibility: Julia 1.9
This feature requires a Julia version of at least 1.9. |
See also the description setproperty!
and getglobal
.
Examples
julia> module M; global a; end;
julia> M.a # то же, что и `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:1
julia> setglobal!(M, :a, 1)
1
julia> M.a
1
#
Core.modifyglobal!
— Function
modifyglobal!(module::Module, name::Symbol, op, x, [order::Symbol=:monotonic]) -> Pair
Atomically performs operations to obtain and set a global variable after applying the op
function.
Compatibility: Julia 1.11
This feature requires a version of Julia at least 1.11. |
See also the description modifyproperty!
and setglobal!
.
#
Core.swapglobal!
— Function
swapglobal!(module::Module, name::Symbol, x, [order::Symbol=:monotonic])
Atomically performs operations for simultaneously obtaining and setting a global variable.
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description swapproperty!
and setglobal!
.
#
Core.setglobalonce!
— Function
setglobalonce!(module::Module, name::Symbol, value,
[success_order::Symbol, [fail_order::Symbol=success_order]) -> success::Bool
Atomically performs operations of assigning a specified value to a global variable, if it has not already been set.
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description setpropertyonce!
and setglobal!
.
#
Core.replaceglobal!
— Function
replaceglobal!(module::Module, name::Symbol, expected, desired,
[success_order::Symbol, [fail_order::Symbol=success_order]) -> (; old, success::Bool)
Atomically performs the operations of obtaining a global variable and conditionally assigning the specified value to it.
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description replaceproperty!
and setglobal!
.
Documentation
(For more information, see the chapter on documentation.)
#
Core.@doc
— Macro
Documentation
Functions, methods, and types can be documented by adding a line before the definition.:
""" # Функция Foo `foo(x)`: Делает Foo с `x`. """ foo(x) = ...
Using the macro @doc
, you can both set and receive documentation and metadata directly. The macro analyzes the code in a special way, so that the documented object can be specified in the next line:
@doc "blah" function foo() ...
By default, documentation is written in Markdown format, 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 as follows:
@doc "foo" function_to_doc @doc "bar" TypeToDoc
For macros, the syntax looks like @doc "macro doc" :(Module.@macro)
, and for string macros — @doc "macro doc" :(string_macro"")
. Without quotes :()
the macro extension is documented.
Obtaining documentation
You can get documentation for functions, macros, and other objects as follows:
@doc foo @doc @time @doc md""
Functions and methods
If the documentation is placed before the method definition (for example, function foo() ...
or foo() = ...
), it refers specifically to this method, and not to the entire function. The documentation of the methods is combined in the order they are defined, forming the documentation for the function.
#
Base.Docs.HTML
— Type
HTML(s)
: Creates an object to display s
in HTML format.
HTML("<div>foo</div>")
You can also use a stream for large amounts of data.:
HTML() do io println(io, "<div>foo</div>") end
The 'HTML` function is currently exported for backward compatibility, but this export is outdated. It is recommended to use this type as `Docs.HTML ` or explicitly import it from `Docs'. |
#
Base.Docs.Text
— Type
Text(s)
: Creates an object to display s
in plain text.
Text("foo")
You can also use a stream for large amounts of data.:
Text() do io println(io, "foo") end
The |
#
Base.Docs.hasdoc
— Function
Docs.hasdoc(mod::Module, sym::Symbol)::Bool
Returns the value true
if sym
in 'mod' has a docstring, or the value false
otherwise.
#
Base.Docs.undocumented_names
— Function
undocumented_names(mod::Module; private=false)
Returns a sorted vector of undocumented characters in the module
(i.e. characters without a docstring). When set to private=false
(by default), only identifiers declared as public
and/or export
are returned, and when set to private=true
, all symbols in the module are returned (with the exception of hidden symbols generated by the compiler and starting with #
).
See also the description names
, Docs.hasdoc
, Base.ispublic
.
Uploading the code
#
Base.identify_package
— Function
Base.identify_package(name::String)::Union{PkgId, Nothing}
Base.identify_package(where::Union{Module,PkgId}, name::String)::Union{PkgId, Nothing}
Identifies a package by its name from the current environment stack, returning its PkgId
or nothing
if it cannot be found.
If only the name
argument is specified, it searches for each environment in the stack and its named direct dependencies.
The 'where` argument specifies the context in which to search for the package: in this case, it first checks whether the name matches the context itself, otherwise it searches for all recursive dependencies (from the resolved manifest of each environment) until the where
context is found, and then the dependency with the appropriate name is identified.
julia> Base.identify_package("Pkg") # Pkg является зависимостью среды по умолчанию
Pkg [44cfe95a-1eb2-52ea-b672-e2afdf69b78f]
julia> using LinearAlgebra
julia> Base.identify_package(LinearAlgebra, "Pkg") # Pkg не является зависимостью линейной алгебры
#
Base.locate_package
— Function
Base.locate_package(pkg::PkgId)::Union{String, Nothing}
The path to the entry point file for the package corresponding to the identifier pkg
, or nothing
if it is not found. See also the description identify_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
— Function
require(into::Module, module::Symbol)
This function is implemented in using
or import
, if the module is not yet defined in `Main'. It can also be called directly to force a reboot of a module, even if it has already been loaded earlier (for example, during interactive library development).
Loads the source code file in the context of the Main
module on each active node, searching for standard file locations. require
is considered a top-level operation, so it sets the current path to include
, but does not use it to search for files (see the function help include
). This function is usually used to load library code and is implicitly invoked by the 'using` command to load packages.
When searching for files, the require' function first searches for the package code in the global array. `LOAD_PATH
. require
requires case-sensitive characters on all platforms, including those with case-insensitive file systems such as macOS and Windows.
For more information about downloading the code, see the sections of the guide dedicated to modules and parallel computing.
#
Base.compilecache
— Function
Base.compilecache(module::PkgId)
Creates a precompiled cache file for the module and all its dependencies. It reduces the package loading time. The cache files are stored in the DEPOT_PATH[1]/compiled
folder. In the section Initialization and pre-compilation of the module important notes are provided.
#
Base.isprecompiled
— Function
Base.isprecompiled(pkg::PkgId; ignore_loaded::Bool=false)
Determines whether a package with the specified PkgId has been precompiled in the active project.
In cases where the dependency versions that were expected are not currently loaded, the same approach is used by default during this check as when loading the code. To ignore loaded modules and get the result as for a new Julia session, specify `ignore_loaded=true'.
Compatibility: Julia 1.10
This feature requires a version of Julia at least 1.10. |
#
Base.get_extension
— Function
get_extension(parent::Module, extension::Symbol)
Returns the module for the extension
for the parent
or returns nothing
if the extension is not loaded.
Internal components
#
Base.GC.gc
— Function
GC.gc([full=true])
Performs garbage collection. The full
argument defines the type of assembly: when fully assembled (by default), all active objects are bypassed (fully labeled) and memory is cleared of all inaccessible objects. With an incremental build, only the so-called "young" objects that are unavailable are cleared from memory.
The garbage collector may decide to perform a full build, even if an incremental build has been requested.
Using it too often is likely to lead to lower performance. |
#
Base.GC.enable
— Function
GC.enable(on::Bool)
Enables or disables garbage collection using a logical argument (true
is enabled, false
is disabled). Returns the previous garbage collection status.
You should be careful to disable garbage collection, as this can lead to an unlimited increase in memory consumption. |
#
Base.GC.@preserve
— Macro
GC.@preserve x1 x2 ... xn expr
Marks objects x1, x2, ...
as used during the evaluation of the expression expr'. It is required only in unsafe code when the expression `expr
_ explicitly uses memory or other resources belonging to one or more objects `x'.
The implicit use of the object x
is any indirect use of resources logically belonging to x
that is invisible to the compiler. Some examples:
-
direct access to the object’s memory via
Ptr
; -
passing a pointer to the object
x
in the callccall
; -
using the resources of object
x
that will be released by the finalizer.
In standard situations, the @preserve
macro usually has no effect on performance, as the lifetime of objects increases slightly. The implementation of the @preserve
macro can have consequences such as protecting dynamically allocated objects from garbage collection.
Examples
When loading by pointer using unsafe_load
, the base object is used implicitly. For example, the object x
is implicitly used by the function unsafe load(p)
in the following code:
julia> let
x = Ref{Int}(101)
p = Base.unsafe_convert(Ptr{Int}, x)
GC.@preserve x unsafe_load(p)
end
101
When passing pointers to ccall, the object referenced by the pointer is used implicitly and must be preserved. (However, keep in mind that usually the object x
is passed to ccall
directly, which is considered explicit usage.)
julia> let
x = "Hello"
p = pointer(x)
Int(GC.@preserve x @ccall strlen(p::Cstring)::Csize_t)
# Предпочтительная альтернатива
Int(@ccall strlen(x::Cstring)::Csize_t)
end
5
#
Base.GC.safepoint
— Function
GC.safepoint()
Adds a point to the program where garbage collection can be performed. It can be useful in rare cases when, in a multithreaded program, some threads allocate memory for objects (and therefore may need garbage collection), while others perform only simple operations (without allocating memory, switching tasks, or I/O). Periodically calling this function on threads that do not allocate memory allows garbage collection.
Compatibility: Julia 1.4
This feature was first implemented in Julia 1.4. |
#
Base.GC.enable_logging
— Function
GC.enable_logging(on::Bool)
When the on argument is set to true, outputs statistics for each garbage collection to the stderr stream.
#
Base.GC.logging_enabled
— Function
GC.logging_enabled()
Determines whether garbage collection logging is enabled using GC.enable_logging
.
#
Base.Meta.lower
— Function
lower(m, x)
Accepts the expression x
and returns an equivalent expression in reduced form for execution in the module m
. See also the description code_lowered
.
#
Base.Meta.parse
— Method
parse(str, start; greedy=true, raise=true, depwarn=true, filename="none")
Analyzes the string containing the expression and returns the expression (which can then be passed to the eval function for execution). start
is the index of the code unit corresponding to the first character in the string str
, from which the analysis should begin (as usual when accessing strings by indexes, this is not the index of the character). If the greedy
argument is set to true
(by default), the parse' function will try to process as much data as possible. Otherwise, processing will stop as soon as a valid expression is analyzed. For incomplete but otherwise syntactically valid expressions, `Expr(:incomplete, "(error message)")
is returned. If the raise
argument is set to true
(by default), an error occurs when syntax errors are detected (excluding incomplete expressions). If the raise
argument is set to false
, the parse' function returns an expression that will generate an error. If the `depwarn
argument is set to false', warnings about decommissioning are not issued. The `filename
argument is used to output diagnostic information when an error occurs.
julia> Meta.parse("(α, β) = 3, 5", 1) # начало строки
(:((α, β) = (3, 5)), 16)
julia> Meta.parse("(α, β) = 3, 5", 1, greedy=false)
(:((α, β)), 9)
julia> Meta.parse("(α, β) = 3, 5", 16) # конец строки
(nothing, 16)
julia> Meta.parse("(α, β) = 3, 5", 11) # индекс 3
(:((3, 5)), 16)
julia> Meta.parse("(α, β) = 3, 5", 11, greedy=false)
(3, 13)
#
Base.Meta.parse
— Method
parse(str; raise=true, depwarn=true, filename="none")
Analyzes as much of the string containing the expression as possible and returns a single expression. If there are more characters after the first expression, an error occurs. If the raise
argument is set to true
(by default), an error occurs when syntax errors are detected; otherwise, the parse
function returns an expression that will cause an error. If the depwarn
argument is set to false', warnings about decommissioning are not issued. The `filename
argument is used to output diagnostic information when an error occurs.
julia> Meta.parse("x = 3")
:(x = 3)
julia> Meta.parse("1.0.2")
ERROR: ParseError:
# Error @ none:1:1
1.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")))
#
Core.QuoteNode
— Type
QuoteNode
The quoted code snippet that does not support interpolation. For more information, see the section of the manual dedicated to QuoteNode.
#
Base.macroexpand
— Function
macroexpand(m::Module, x; recursive=true)
Accepts the expression x
and returns an equivalent expression in which all macros have been deleted (expanded) for execution in the m
module. The named recursive
argument determines whether deeper levels of nested macros are expanded. This is demonstrated in the following example:
julia> module M
macro m1()
42
end
macro m2()
:(@m1())
end
end
M
julia> macroexpand(M, :(@m2()), recursive=true)
42
julia> macroexpand(M, :(@m2()), recursive=false)
:(#= REPL[16]:6 =# M.@m1)
#
Base.@macroexpand
— Macro
@macroexpand [mod,] ex
Returns an equivalent expression in which all macros have been deleted (expanded). If two arguments are specified, the first contains the module in which the calculation is to be performed.
Between the macro @macroexpand
and the function macroexpand
there are differences.
-
Function 'macroexpand` takes the named argument
recursive
, and the macro@macroexpand
always works recursively. A version of this macro without recursion —@macroexpand1
. -
The function 'macroexpand` has an explicitly specified
module
argument, and the macro@macroexpand
always performs an extension relative to the module in which it is called.
This is clearly seen in the following example.
julia> module M
macro m()
1
end
function f()
(@macroexpand(@m),
macroexpand(M, :(@m)),
macroexpand(Main, :(@m))
)
end
end
M
julia> macro m()
2
end
@m (macro with 1 method)
julia> M.f()
(1, 1, 2)
When using @macroexpand
, the expression expands where the macro @macroexpand
is used in the code (in the example, this is the M
module). When using `macroexpand', the expression is expanded in the module specified in the first argument.
Compatibility: Julia 1.11
A form with two arguments requires a Julia version of at least 1.11. |
#
Base.code_lowered
— Function
code_lowered(f, types; generated=true, debuginfo=:default)
Returns an array of reduced forms (intermediate representations) for methods corresponding to the specified universal function and type signature.
If the generated
argument is false
, the returned instances of CodeInfo' correspond to standard implementations. If there is no standard implementation, an error occurs. If the `generated
argument is true
, these CodeInfo
instances correspond to the method bodies that result from extending generators.
The named argument `debuginfo' defines the amount of code metadata in the output.
Please note: if the types are in types
are not final, when the generated
argument is true
and any corresponding method is marked as @generated
, an error occurs.
#
Base.code_typed
— Function
code_typed(f, types; kw...)
Returns an array of reduced forms (intermediate representations) with type output for methods corresponding to the specified universal function and type signature.
Named arguments
-
optimize::Bool = true
: optional, determines whether additional optimizations such as embedding are applied. -
debuginfo::Symbol = :default
: optional, defines the amount of code metadata in the output data. Possible values are ':source` and `:none'.
Internal named arguments
This section is intended only for those who understand the internal principles of the Julia compiler.
-
world::UInt = Base.get_world_counter()
: optional, defines the "age of the world" used when searching for methods. If this argument is omitted, the current "age of the world" is used. -
interp::Core.Compiler.AbstractInterpreter = Core.Compiler.NativeInterpreter(world)
: optional, defines the abstract interpreter used. If this argument is not specified, a custom interpreter is used.
Examples
The types of arguments can be specified as a tuple to get the corresponding result of the 'code_typed` function.
julia> code_typed(+, (Float64, Float64))
1-element Vector{Any}:
CodeInfo(
1 ─ %1 = Base.add_float(x, y)::Float64
└── return %1
) => Float64
#
Base.precompile
— Function
precompile(f, argtypes::Tuple{Vararg{Any}})
Compiles the specified function f
taking into account the types of arguments passed as a tuple to argtypes
, but does not execute it.
precompile(f, argtypes::Tuple{Vararg{Any}}, m::Method)
Performs a pre-compilation of a specific method for the specified argument types. You can use a different method for pre-compilation than the one that is usually selected during dispatch, thus simulating `invoke'.
#
Base.jit_total_bytes
— Function
Base.jit_total_bytes()
Returns the total amount of memory (in bytes) allocated by the JIT compiler,
Metafunctions
#
Base.Meta.quot
— Function
Meta.quot(ex)::Expr
Quotes the expression ex
, creating an expression with the heading quote'. It can be used, for example, to represent objects of the type `Expr
in AST. See also the section of the manual devoted to QuoteNode.
Examples
julia> eval(Meta.quot(:x))
:x
julia> dump(Meta.quot(:x))
Expr
head: Symbol quote
args: Array{Any}((1,))
1: Symbol x
julia> eval(Meta.quot(:(1+2)))
:(1 + 2)
#
Base.isexpr
— Function
Meta.isexpr(ex, head[, n])::Bool
Returns the value true
if ex
is an Expr
object of the specified head
type. You can also check whether the number of its arguments is equal to the value n
. The 'head` argument can contain an object of type Symbol
or a collection of Symbol
objects. For example, to check whether a function call expression has been passed to the macro, you can use 'isexpr(ex, :call)`.
Examples
julia> ex = :(f(x))
:(f(x))
julia> Meta.isexpr(ex, :block)
false
julia> Meta.isexpr(ex, :call)
true
julia> Meta.isexpr(ex, [:block, :call]) # несколько возможных заголовков
true
julia> Meta.isexpr(ex, :call, 1)
false
julia> Meta.isexpr(ex, :call, 2)
true
#
Base.isidentifier
— Function
isidentifier(s) -> Bool
Determines whether the character or string s
contains characters that are parsed in Julia code as a normal valid name (rather than a binary or unary operator). See also the description Base.isoperator
.
In Julia, any character sequences are allowed in Symbol
objects (except \0
), so macros automatically use variable names with the #
symbol to avoid name conflicts with the surrounding code. In order for the analyzer to recognize variables, a limited set of characters is used (which is significantly expanded due to Unicode). The 'isidentifier()` function allows you to directly request from the analyzer whether the Symbol object contains valid characters.
Examples
julia> Meta.isidentifier(:x), Meta.isidentifier("1x")
(true, false)
#
Base.isoperator
— Function
isoperator(s::Symbol)
Returns the value true
if the character can be used as an operator; otherwise, it returns `false'.
Examples
julia> Meta.isoperator(:+), Meta.isoperator(:f)
(true, false)
#
Base.isunaryoperator
— Function
isunaryoperator(s::Symbol)
Returns the value true
if the character can be used as a unary (prefix) operator; otherwise, it returns `false'.
Examples
julia> Meta.isunaryoperator(:-), Meta.isunaryoperator(:√), Meta.isunaryoperator(:f)
(true, true, false)
#
Base.isbinaryoperator
— Function
isbinaryoperator(s::Symbol)
Returns the value true
if the character can be used as a binary (infix) operator; otherwise, it returns `false'.
Examples
julia> Meta.isbinaryoperator(:-), Meta.isbinaryoperator(:√), Meta.isbinaryoperator(:f)
(true, false, false)
#
Base.Meta.show_sexpr
— Function
Meta.show_sexpr([io::IO,], ex)
Outputs the ex
image as a Lisp-style S-expression.
Examples
julia> Meta.show_sexpr(:(f(x, g(y,z))))
(:call, :f, :x, (:call, :g, :y, :z))