Essentials

Essentials

Introduction

The Julia standard library contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.

Some general notes:

Getting Around

Base.exitFunction.
exit([code])

Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.

source
Base.quitFunction.
quit()

Quit the program indicating that the processes completed successfully. This function calls exit(0) (see exit).

source
Base.atexitFunction.
atexit(f)

Register a zero-argument function f() to be called at process exit. atexit() hooks are called in last in first out (LIFO) order and run before object finalizers.

source
Base.atreplinitFunction.
atreplinit(f)

Register a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The argument of f is the REPL object. This function should be called from within the .juliarc.jl initialization file.

source
Base.isinteractiveFunction.
isinteractive() -> Bool

Determine whether Julia is running an interactive session.

source
Base.whosFunction.
whos(io::IO=STDOUT, m::Module=current_module(), pattern::Regex=r"")

Print information about exported global variables in a module, optionally restricted to those matching pattern.

The memory consumption estimate is an approximate lower bound on the size of the internal structure of the object.

source
Base.summarysizeFunction.
Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int

Compute the amount of memory used by all unique objects reachable from the argument.

Keyword Arguments

  • exclude: specifies the types of objects to exclude from the traversal.

  • chargeall: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.

source
Base.editMethod.
edit(path::AbstractString, line::Integer=0)

Edit a file or directory optionally providing a line number to edit the file at. Returns to the julia prompt when you quit the editor. The editor can be changed by setting JULIA_EDITOR, VISUAL or EDITOR as an environment variable.

source
Base.editMethod.
edit(function, [types])

Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. The editor can be changed by setting JULIA_EDITOR, VISUAL or EDITOR as an environment variable.

source
Base.@editMacro.
@edit

Evaluates the arguments to the function or macro call, determines their types, and calls the edit function on the resulting expression.

source
Base.lessMethod.
less(file::AbstractString, [line::Integer])

Show a file using the default pager, optionally providing a starting line number. Returns to the julia prompt when you quit the pager.

source
Base.lessMethod.
less(function, [types])

Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.

source
Base.@lessMacro.
@less

Evaluates the arguments to the function or macro call, determines their types, and calls the less function on the resulting expression.

source
Base.clipboardMethod.
clipboard(x)

Send a printed form of x to the operating system clipboard ("copy").

source
Base.clipboardMethod.
clipboard() -> AbstractString

Return a string with the contents of the operating system clipboard ("paste").

source
Base.reloadFunction.
reload(name::AbstractString)

Force reloading of a package, even if it has been loaded before. This is intended for use during package development as code is modified.

source
Base.requireFunction.
require(module::Symbol)

This function is part of the implementation of using / import, if a module is not already defined in Main. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).

Loads a source file, in the context of the Main module, on every active node, searching standard locations for files. require is considered a top-level operation, so it sets the current include path but does not use it to search for files (see help for include). This function is typically used to load library code, and is implicitly called by using to load packages.

When searching for files, require first looks for package code under Pkg.dir(), then tries paths in the global array LOAD_PATH. require is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.

source
Base.compilecacheFunction.
Base.compilecache(module::String)

Creates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored in LOAD_CACHE_PATH[1], which defaults to ~/.julia/lib/VERSION. See Module initialization and precompilation for important notes.

source
Base.__precompile__Function.
__precompile__(isprecompilable::Bool=true)

Specify whether the file calling this function is precompilable. If isprecompilable is true, then __precompile__ throws an exception when the file is loaded by using/import/require unless the file is being precompiled, and in a module file it causes the module to be automatically precompiled when it is imported. Typically, __precompile__() should occur before the module declaration in the file, or better yet VERSION >= v"0.4" && __precompile__() in order to be backward-compatible with Julia 0.3.

If a module or file is not safely precompilable, it should call __precompile__(false) in order to throw an error if Julia attempts to precompile it.

__precompile__() should not be used in a module unless all of its dependencies are also using __precompile__(). Failure to do so can result in a runtime error when loading the module.

source
Base.includeFunction.
include(path::AbstractString)

Evaluate the contents of the input source file in the current context. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.

source
Base.include_stringFunction.
include_string(code::AbstractString, filename::AbstractString="string")

Like include, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done.

source
include_dependency(path::AbstractString)

In a module, declare that the file specified by path (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if this file changes.

This is only needed if your module depends on a file that is not used via include. It has no effect outside of compilation.

source
Base.Docs.aproposFunction.
apropos(string)

Search through all documentation for a string, ignoring case.

source
Base.whichMethod.
which(f, types)

Returns the method of f (a Method object) that would be called for arguments of the given types.

If types is an abstract type, then the method that would be called by invoke is returned.

source
Base.whichMethod.
which(symbol)

Return the module in which the binding for the variable referenced by symbol was created.

source
Base.@whichMacro.
@which

Applied to a function or macro call, it evaluates the arguments to the specified call, and returns the Method object for the method that would be called for those arguments. Applied to a variable, it returns the module in which the variable was bound. It calls out to the which function.

source
Base.methodsFunction.
methods(f, [types])

Returns the method table for f.

If types is specified, returns an array of methods whose types match.

source
Base.methodswithFunction.
methodswith(typ[, module or function][, showparents::Bool=false])

Return an array of methods with an argument of type typ.

The optional second argument restricts the search to a particular module or function (the default is all modules, starting from Main).

If optional showparents is true, also return arguments with a parent type of typ, excluding type Any.

source
Base.@showMacro.
@show

Show an expression and result, returning the result.

source
Base.versioninfoFunction.
versioninfo(io::IO=STDOUT, verbose::Bool=false)

Print information about the version of Julia in use. If the verbose argument is true, detailed system information is shown as well.

source
Base.workspaceFunction.
workspace()

Replace the top-level module (Main) with a new one, providing a clean workspace. The previous Main module is made available as LastMain. A previously-loaded package can be accessed using a statement such as using LastMain.Package.

This function should only be used interactively.

source
ansKeyword.
ans

A variable referring to the last computed value, automatically set at the interactive prompt.

source

All Objects

Core.:===Function.
===(x,y) -> Bool
≡(x,y) -> Bool

Determine whether x and y are identical, in the sense that no program could distinguish them. Compares mutable objects by address in memory, and compares immutable objects (such as numbers) by contents at the bit level. This function is sometimes called egal.

julia> a = [1, 2]; b = [1, 2];

julia> a == b
true

julia> a === b
false

julia> a === a
true
source
Core.isaFunction.
isa(x, type) -> Bool

Determine whether x is of the given type. Can also be used as an infix operator, e.g. x isa type.

source
Base.isequalMethod.
isequal(x, y)

Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn't have these floating-point subtleties then you probably only need to define ==.

isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

This typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).

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
source
Base.isequalMethod.
isequal(x, y)

Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn't have these floating-point subtleties then you probably only need to define ==.

isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

This typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).

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
source
isequal(x::Nullable, y::Nullable)

If neither x nor y is null, compare them according to their values (i.e. isequal(get(x), get(y))). Else, return true if both arguments are null, and false if one is null but not the other: nulls are considered equal.

source
Base.islessFunction.
isless(x, y)

Test whether x is less than y, according to a canonical total order. Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. This is the default comparison used by sort. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as NaN.

source
Base.islessMethod.
isless(x::Nullable, y::Nullable)

If neither x nor y is null, compare them according to their values (i.e. isless(get(x), get(y))). Else, return true if only y is null, and false otherwise: nulls are always considered greater than non-nulls, but not greater than another null.

source
Base.ifelseFunction.
ifelse(condition::Bool, x, y)

Return x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using ifelse instead of an if statement can eliminate the branch in generated code and provide higher performance in tight loops.

julia> ifelse(1 > 2, 1, 2)
2
source
Base.lexcmpFunction.
lexcmp(x, y)

Compare x and y lexicographically and return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. This function should be defined for lexicographically comparable types, and lexless will call lexcmp by default.

julia> lexcmp("abc", "abd")
-1

julia> lexcmp("abc", "abc")
0
source
Base.lexlessFunction.
lexless(x, y)

Determine whether x is lexicographically less than y.

julia> lexless("abc", "abd")
true
source
Core.typeofFunction.
typeof(x)

Get the concrete type of x.

source
Core.tupleFunction.
tuple(xs...)

Construct a tuple of the given objects.

Example

julia> tuple(1, 'a', pi)
(1, 'a', π = 3.1415926535897...)
source
Base.ntupleFunction.
ntuple(f::Function, n::Integer)

Create a tuple of length n, computing each element as f(i), where i is the index of the element.

julia> ntuple(i -> 2*i, 4)
(2, 4, 6, 8)
source
Base.object_idFunction.
object_id(x)

Get a hash value for x based on object identity. object_id(x)==object_id(y) if x === y.

source
Base.hashFunction.
hash(x[, h::UInt])

Compute an integer hash code such that isequal(x,y) implies hash(x)==hash(y). The optional second argument h is a hash code to be mixed with the result.

New types should implement the 2-argument form, typically by calling the 2-argument hash method recursively in order to mix hashes of the contents with each other (and with h). Typically, any type that implements hash should also implement its own == (hence isequal) to guarantee the property mentioned above.

source
Base.finalizerFunction.
finalizer(x, f)

Register a function f(x) to be called when there are no program-accessible references to x. The type of x must be a mutable struct, otherwise the behavior of this function is unpredictable.

source
Base.finalizeFunction.
finalize(x)

Immediately run finalizers registered for object x.

source
Base.copyFunction.
copy(x)

Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.

source
Base.deepcopyFunction.
deepcopy(x)

Create a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy on an object should generally have the same effect as serializing and then deserializing it.

As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.

While it isn't normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::ObjectIdDict) (which shouldn't otherwise be used), where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion. Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be updated as appropriate before returning.

source
Core.isdefinedFunction.
isdefined([m::Module,] s::Symbol)
isdefined(object, s::Symbol)
isdefined(object, index::Int)

Tests whether an assignable location is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index. With a single symbol argument, tests whether a global variable with that name is defined in current_module().

source
Base.convertFunction.
convert(T, x)

Convert x to a value of type T.

If T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not integer-valued, or is outside the range supported by T.

Examples

julia> convert(Int, 3.0)
3

julia> convert(Int, 3.5)
ERROR: InexactError()
Stacktrace:
 [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679

If T is a AbstractFloat or Rational type, then it will return the closest value to x representable by T.

julia> x = 1/3
0.3333333333333333

julia> convert(Float32, x)
0.33333334f0

julia> convert(Rational{Int32}, x)
1//3

julia> convert(Rational{Int64}, x)
6004799503160661//18014398509481984

If T is a collection type and x a collection, the result of convert(T, x) may alias x.

julia> x = Int[1,2,3];

julia> y = convert(Vector{Int}, x);

julia> y === x
true

Similarly, if T is a composite type and x a related instance, the result of convert(T, x) may alias part or all of x.

julia> x = speye(5);

julia> typeof(x)
SparseMatrixCSC{Float64,Int64}

julia> y = convert(SparseMatrixCSC{Float64,Int64}, x);

julia> z = convert(SparseMatrixCSC{Float32,Int64}, y);

julia> y === x
true

julia> z === x
false

julia> z.colptr === x.colptr
true
source
Base.promoteFunction.
promote(xs...)

Convert all arguments to their common promotion type (if any), and return them all (as a tuple).

Example

julia> promote(Int8(1), Float16(4.5), Float32(4.1))
(1.0f0, 4.5f0, 4.1f0)
source
Base.oftypeFunction.
oftype(x, y)

Convert y to the type of x (convert(typeof(x), y)).

source
Base.widenFunction.
widen(x)

If x is a type, return a "larger" type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise x is converted to widen(typeof(x)).

Examples

julia> widen(Int32)
Int64

julia> widen(1.5f0)
1.5
source
Base.identityFunction.
identity(x)

The identity function. Returns its argument.

julia> identity("Well, what did you expect?")
"Well, what did you expect?"
source

Types

Base.supertypeFunction.
supertype(T::DataType)

Return the supertype of DataType T.

julia> supertype(Int32)
Signed
source
Core.issubtypeFunction.
issubtype(type1, type2)

Return true if and only if all values of type1 are also of type2. Can also be written using the <: infix operator as type1 <: type2.

Examples

julia> issubtype(Int8, Int32)
false

julia> Int8 <: Integer
true
source
Base.:<:Function.
<:(T1, T2)

Subtype operator, equivalent to issubtype(T1, T2).

julia> Float64 <: AbstractFloat
true

julia> Vector{Int} <: AbstractArray
true

julia> Matrix{Float64} <: Matrix{AbstractFloat}
false
source
Base.:>:Function.
>:(T1, T2)

Supertype operator, equivalent to issubtype(T2, T1).

source
Base.subtypesFunction.
subtypes(T::DataType)

Return a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.

julia> subtypes(Integer)
4-element Array{Union{DataType, UnionAll},1}:
 BigInt
 Bool
 Signed
 Unsigned
source
Base.typeminFunction.
typemin(T)

The lowest value representable by the given (real) numeric DataType T.

Examples

julia> typemin(Float16)
-Inf16

julia> typemin(Float32)
-Inf32
source
Base.typemaxFunction.
typemax(T)

The highest value representable by the given (real) numeric DataType.

source
Base.realminFunction.
realmin(T)

The smallest in absolute value non-subnormal value representable by the given floating-point DataType T.

source
Base.realmaxFunction.
realmax(T)

The highest finite value representable by the given floating-point DataType T.

Examples

julia> realmax(Float16)
Float16(6.55e4)

julia> realmax(Float32)
3.4028235f38
source
Base.maxintfloatFunction.
maxintfloat(T)

The largest integer losslessly representable by the given floating-point DataType T.

source
maxintfloat(T, S)

The largest integer losslessly representable by the given floating-point DataType T that also does not exceed the maximum integer representable by the integer DataType S.

source
Base.sizeofMethod.
sizeof(T)

Size, in bytes, of the canonical binary representation of the given DataType T, if any.

Examples

julia> sizeof(Float32)
4

julia> sizeof(Complex128)
16

If T does not have a specific size, an error is thrown.

julia> sizeof(Base.LinAlg.LU)
ERROR: argument is an abstract type; size is indeterminate
Stacktrace:
 [1] sizeof(::Type{T} where T) at ./essentials.jl:159
source
Base.epsMethod.
eps(::Type{T}) where T<:AbstractFloat
eps()

Returns the machine epsilon of the floating point type T (T = Float64 by default). This is defined as the gap between 1 and the next largest value representable by T, and is equivalent to eps(one(T)).

julia> eps()
2.220446049250313e-16

julia> eps(Float32)
1.1920929f-7

julia> 1.0 + eps()
1.0000000000000002

julia> 1.0 + eps()/2
1.0
source
Base.epsMethod.
eps(x::AbstractFloat)

Returns the unit in last place (ulp) of x. This is the distance between consecutive representable floating point values at x. In most cases, if the distance on either side of x is different, then the larger of the two is taken, that is

eps(x) == max(x-prevfloat(x), nextfloat(x)-x)

The exceptions to this rule are the smallest and largest finite values (e.g. nextfloat(-Inf) and prevfloat(Inf) for Float64), which round to the smaller of the values.

The rationale for this behavior is that eps bounds the floating point rounding error. Under the default RoundNearest rounding mode, if $y$ is a real number and $x$ is the nearest floating point number to $y$, then

\[|y-x| \leq \operatorname{eps}(x)/2.\]
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)      # largest finite Float64
1.7976931348623157e308

julia> x + eps(x)/2            # rounds up
Inf

julia> x + prevfloat(eps(x)/2) # rounds down
1.7976931348623157e308
source
Base.promote_typeFunction.
promote_type(type1, type2)

Determine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists to which both types can be promoted losslessly, some loss is tolerated; for example, promote_type(Int64, Float64) returns Float64 even though strictly, not all Int64 values can be represented exactly as Float64 values.

julia> promote_type(Int64, Float64)
Float64

julia> promote_type(Int32, Int64)
Int64

julia> promote_type(Float32, BigInt)
BigFloat
source
Base.promote_ruleFunction.
promote_rule(type1, type2)

Specifies what type should be used by promote when given values of types type1 and type2. This function should not be called directly, but should have definitions added to it for new types as appropriate.

source
Core.getfieldFunction.
getfield(value, name::Symbol)

Extract a named field from a value of composite type. The syntax a.b calls getfield(a, :b).

Example

julia> a = 1//2
1//2

julia> getfield(a, :num)
1
source
Core.setfield!Function.
setfield!(value, name::Symbol, x)

Assign x to a named field in value of composite type. The syntax a.b = c calls setfield!(a, :b, c).

source
Base.fieldoffsetFunction.
fieldoffset(type, i)

The byte offset of field i of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct:

julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:nfields(T)];

julia> structinfo(Base.Filesystem.StatStruct)
12-element Array{Tuple{UInt64,Symbol,DataType},1}:
 (0x0000000000000000, :device, UInt64)
 (0x0000000000000008, :inode, UInt64)
 (0x0000000000000010, :mode, UInt64)
 (0x0000000000000018, :nlink, Int64)
 (0x0000000000000020, :uid, UInt64)
 (0x0000000000000028, :gid, UInt64)
 (0x0000000000000030, :rdev, UInt64)
 (0x0000000000000038, :size, Int64)
 (0x0000000000000040, :blksize, Int64)
 (0x0000000000000048, :blocks, Int64)
 (0x0000000000000050, :mtime, Float64)
 (0x0000000000000058, :ctime, Float64)
source
Core.fieldtypeFunction.
fieldtype(T, name::Symbol | index::Int)

Determine the declared type of a field (specified by name or index) in a composite DataType T.

julia> struct Foo
           x::Int64
           y::String
       end

julia> fieldtype(Foo, :x)
Int64

julia> fieldtype(Foo, 2)
String
source
Base.isimmutableFunction.
isimmutable(v)

Return true iff value v is immutable. See Mutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of DataType is mutable.

julia> isimmutable(1)
true

julia> isimmutable([1,2])
false
source
Base.isbitsFunction.
isbits(T)

Return true if T is a "plain data" type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such as UInt8, Float64, and Complex{Float64}.

julia> isbits(Complex{Float64})
true

julia> isbits(Complex)
false
source
Base.isleaftypeFunction.
isleaftype(T)

Determine whether T's only subtypes are itself and Union{}. This means T is a concrete type that can have instances.

julia> isleaftype(Complex)
false

julia> isleaftype(Complex{Float32})
true

julia> isleaftype(Vector{Complex})
true

julia> isleaftype(Vector{Complex{Float32}})
true
source
Base.typejoinFunction.
typejoin(T, S)

Compute a type that contains both T and S.

source
Base.typeintersectFunction.
typeintersect(T, S)

Compute a type that contains the intersection of T and S. Usually this will be the smallest such type or one close to it.

source
Base.ValType.
Val{c}

Create a "value type" out of c, which must be an isbits value. The intent of this construct is to be able to dispatch on constants, e.g., f(Val{false}) allows you to dispatch directly (at compile-time) to an implementation f(::Type{Val{false}}), without having to test the boolean value at runtime.

source
Base.Enums.@enumMacro.
@enum EnumName[::BaseType] EnumValue1[=x] EnumValue2[=y]

Create an Enum{BaseType} subtype with name EnumName and enum member values of EnumValue1 and EnumValue2 with optional assigned values of x and y, respectively. EnumName can be used just like other types and enum member values as regular values, such as

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"

BaseType, which defaults to Int32, must be a primitive subtype of Integer. Member values can be converted between the enum type and BaseType. read and write perform these conversions automatically.

source
Base.instancesFunction.
instances(T::Type)

Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see @enum).

julia> @enum Colors Red Blue Green

julia> instances(Colors)
(Red::Colors = 0, Blue::Colors = 1, Green::Colors = 2)
source

Generic Functions

Core.FunctionType.
Function

Abstract type of all functions.

julia> isa(+, Function)
true

julia> typeof(sin)
Base.#sin

julia> ans <: Function
true
source
Base.method_existsFunction.
method_exists(f, Tuple type, world=typemax(UInt)) -> Bool

Determine whether the given generic function has a method matching the given Tuple of argument types with the upper bound of world age given by world.

julia> method_exists(length, Tuple{Array})
true
source
Core.applicableFunction.
applicable(f, args...) -> Bool

Determine whether the given generic function has a method applicable to the given arguments.

Examples

julia> function f(x, y)
           x + y
       end;

julia> applicable(f, 1)
false

julia> applicable(f, 1, 2)
true
source
Core.invokeFunction.
invoke(f, types <: Tuple, args...)

Invoke a method for the given generic function matching the specified types, on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).

source
Base.invokelatestFunction.
invokelatest(f, args...)

Calls f(args...), but guarantees that the most recent method of f will be executed. This is useful in specialized circumstances, e.g. long-running event loops or callback functions that may call obsolete versions of a function f. (The drawback is that invokelatest is somewhat slower than calling f directly, and the type of the result cannot be inferred by the compiler.)

source
Base.:|>Function.
|>(x, f)

Applies a function to the preceding argument. This allows for easy function chaining.

julia> [1:5;] |> x->x.^2 |> sum |> inv
0.01818181818181818
source
Base.:∘Function.
f ∘ g

Compose functions: i.e. (f ∘ g)(args...) means f(g(args...)). The symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing \circ<tab>. Example:

julia> map(uppercase∘hex, 250:255)
6-element Array{String,1}:
 "FA"
 "FB"
 "FC"
 "FD"
 "FE"
 "FF"
source

Syntax

Core.evalFunction.
eval([m::Module], expr::Expr)

Evaluate an expression in the given module and return the result. Every Module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.

source
Base.@evalMacro.
@eval [mod,] ex

Evaluate an expression with values interpolated into it using eval. If two arguments are provided, the first is the module to evaluate in.

source
Base.evalfileFunction.
evalfile(path::AbstractString, args::Vector{String}=String[])

Load the file using include, evaluate all expressions, and return the value of the last one.

source
Base.escFunction.
esc(e::ANY)

Only valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the Macros section of the Metaprogramming chapter of the manual for more details and examples.

source
Base.@inboundsMacro.
@inbounds(blk)

Eliminates array bounds checking within expressions.

In the example below the bound check of array A is skipped to improve performance.

function sum(A::AbstractArray)
    r = zero(eltype(A))
    for i = 1:length(A)
        @inbounds r += A[i]
    end
    return r
end
Warning

Using @inbounds may return incorrect results/crashes/corruption for out-of-bounds indices. The user is responsible for checking it manually.

source
Base.@inlineMacro.
@inline

Give a hint to the compiler that this function is worth inlining.

Small functions typically do not need the @inline annotation, as the compiler does it automatically. By using @inline on bigger functions, an extra nudge can be given to the compiler to inline it. This is shown in the following example:

@inline function bigfunction(x)
    #=
        Function Definition
    =#
end
source
Base.@noinlineMacro.
@noinline

Prevents the compiler from inlining a function.

Small functions are typically inlined automatically. By using @noinline on small functions, auto-inlining can be prevented. This is shown in the following example:

@noinline function smallfunction(x)
    #=
        Function Definition
    =#
end
source
Base.gensymFunction.
gensym([tag])

Generates a symbol which will not conflict with other variable names.

source
Base.@gensymMacro.
@gensym

Generates a gensym symbol for a variable. For example, @gensym x y is transformed into x = gensym("x"); y = gensym("y").

source
Base.@pollyMacro.
@polly

Tells the compiler to apply the polyhedral optimizer Polly to a function.

source
Base.parseMethod.
parse(str, start; greedy=true, raise=true)

Parse the expression string and return an expression (which could later be passed to eval for execution). start is the index of the first character to start parsing. If greedy is true (default), parse will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return Expr(:incomplete, "(error message)"). If raise is true (default), syntax errors other than incomplete expressions will raise an error. If raise is false, parse will return an expression that will raise an error upon evaluation.

julia> parse("x = 3, y = 5", 7)
(:(y = 5), 13)

julia> parse("x = 3, y = 5", 5)
(:((3, y) = 5), 13)
source
Base.parseMethod.
parse(str; raise=true)

Parse the expression string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If raise is true (default), syntax errors will raise an error; otherwise, parse will return an expression that will raise an error upon evaluation.

julia> parse("x = 3")
:(x = 3)

julia> parse("x = ")
:($(Expr(:incomplete, "incomplete: premature end of input")))

julia> parse("1.0.2")
ERROR: ParseError("invalid numeric constant \"1.0.\"")
Stacktrace:
[...]

julia> parse("1.0.2"; raise = false)
:($(Expr(:error, "invalid numeric constant \"1.0.\"")))
source

Nullables

Base.NullableType.
Nullable(x, hasvalue::Bool=true)

Wrap value x in an object of type Nullable, which indicates whether a value is present. Nullable(x) yields a non-empty wrapper and Nullable{T}() yields an empty instance of a wrapper that might contain a value of type T.

Nullable(x, false) yields Nullable{typeof(x)}() with x stored in the result's value field.

Examples

julia> Nullable(1)
Nullable{Int64}(1)

julia> Nullable{Int64}()
Nullable{Int64}()

julia> Nullable(1, false)
Nullable{Int64}()

julia> dump(Nullable(1, false))
Nullable{Int64}
  hasvalue: Bool false
  value: Int64 1
source
Base.getMethod.
get(x::Nullable[, y])

Attempt to access the value of x. Returns the value if it is present; otherwise, returns y if provided, or throws a NullException if not.

source
Base.isnullFunction.
isnull(x)

Return whether or not x is null for Nullable x; return false for all other x.

Examples

julia> x = Nullable(1, false)
Nullable{Int64}()

julia> isnull(x)
true

julia> x = Nullable(1, true)
Nullable{Int64}(1)

julia> isnull(x)
false

julia> x = 1
1

julia> isnull(x)
false
source
Base.unsafe_getFunction.
unsafe_get(x)

Return the value of x for Nullable x; return x for all other x.

This method does not check whether or not x is null before attempting to access the value of x for x::Nullable (hence "unsafe").

julia> x = Nullable(1)
Nullable{Int64}(1)

julia> unsafe_get(x)
1

julia> x = Nullable{String}()
Nullable{String}()

julia> unsafe_get(x)
ERROR: UndefRefError: access to undefined reference
Stacktrace:
 [1] unsafe_get(::Nullable{String}) at ./nullable.jl:125

julia> x = 1
1

julia> unsafe_get(x)
1
source

System

Base.runFunction.
run(command, args...)

Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non-zero status.

source
Base.spawnFunction.
spawn(command)

Run a command object asynchronously, returning the resulting Process object.

source
Base.DevNullConstant.
DevNull

Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows. Usage:

run(pipeline(`cat test.txt`, DevNull))
source
Base.successFunction.
success(command)

Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.

source
Base.process_runningFunction.
process_running(p::Process)

Determine whether a process is currently running.

source
Base.process_exitedFunction.
process_exited(p::Process)

Determine whether a process has exited.

source
Base.killMethod.
kill(p::Process, signum=SIGTERM)

Send a signal to a process. The default is to terminate the process.

source
Sys.set_process_title(title::AbstractString)

Set the process title. No-op on some operating systems.

source
Sys.get_process_title()

Get the process title. On some systems, will always return an empty string.

source
Base.readandwriteFunction.
readandwrite(command)

Starts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the output stream and input stream of the process, and the process object itself.

source
Base.ignorestatusFunction.
ignorestatus(command)

Mark a command object so that running it will not throw an error if the result code is non-zero.

source
Base.detachFunction.
detach(command)

Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.

source
Base.CmdType.
Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)

Construct a new Cmd object, representing an external program and arguments, from cmd, while changing the settings of the optional keyword arguments:

  • ignorestatus::Bool: If true (defaults to false), then the Cmd will not throw an error if the return code is nonzero.

  • detach::Bool: If true (defaults to false), then the Cmd will be run in a new process group, allowing it to outlive the julia process and not have Ctrl-C passed to it.

  • windows_verbatim::Bool: If true (defaults to false), then on Windows the Cmd will send a command-line string to the process with no quoting or escaping of arguments, even arguments containing spaces. (On Windows, arguments are sent to a program as a single "command-line" string, and programs are responsible for parsing it into arguments. By default, empty arguments and arguments with spaces or tabs are quoted with double quotes " in the command line, and \ or " are preceded by backslashes. windows_verbatim=true is useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.

  • windows_hide::Bool: If true (defaults to false), then on Windows no new console window is displayed when the Cmd is executed. This has no effect if a console is already open or on non-Windows systems.

  • env: Set environment variables to use when running the Cmd. env is either a dictionary mapping strings to strings, an array of strings of the form "var=val", an array or tuple of "var"=>val pairs, or nothing. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then set env["var"]=val as desired.

  • dir::AbstractString: Specify a working directory for the command (instead of the current directory).

For any keywords that are not specified, the current settings from cmd are used. Normally, to create a Cmd object in the first place, one uses backticks, e.g.

Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)
source
Base.setenvFunction.
setenv(command::Cmd, env; dir="")

Set environment variables to use when running the given command. env is either a dictionary mapping strings to strings, an array of strings of the form "var=val", or zero or more "var"=>val pair arguments. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then setting env["var"]=val as desired, or use withenv.

The dir keyword argument can be used to specify a working directory for the command.

source
Base.withenvFunction.
withenv(f::Function, kv::Pair...)

Execute f() in an environment that is temporarily modified (not replaced as in setenv) by zero or more "var"=>val arguments kv. withenv is generally used via the withenv(kv...) do ... end syntax. A value of nothing can be used to temporarily unset an environment variable (if it is set). When withenv returns, the original environment has been restored.

source
Base.pipelineMethod.
pipeline(from, to, ...)

Create a pipeline from a data source to a destination. The source and destination can be commands, I/O streams, strings, or results of other pipeline calls. At least one argument must be a command. Strings refer to filenames. When called with more than two arguments, they are chained together from left to right. For example pipeline(a,b,c) is equivalent to pipeline(pipeline(a,b),c). This provides a more concise way to specify multi-stage pipelines.

Examples:

run(pipeline(`ls`, `grep xyz`))
run(pipeline(`ls`, "out.txt"))
run(pipeline("out.txt", `grep xyz`))
source
Base.pipelineMethod.
pipeline(command; stdin, stdout, stderr, append=false)

Redirect I/O to or from the given command. Keyword arguments specify which of the command's streams should be redirected. append controls whether file output appends to the file. This is a more general version of the 2-argument pipeline function. pipeline(from, to) is equivalent to pipeline(from, stdout=to) when from is a command, and to pipeline(to, stdin=from) when from is another kind of data source.

Examples:

run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt"))
run(pipeline(`update`, stdout="log.txt", append=true))
source
Base.Libc.gethostnameFunction.
gethostname() -> AbstractString

Get the local machine's host name.

source
Base.getipaddrFunction.
getipaddr() -> IPAddr

Get the IP address of the local machine.

source
Base.Libc.getpidFunction.
getpid() -> Int32

Get Julia's process ID.

source
Base.Libc.timeMethod.
time()

Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.

source
Base.time_nsFunction.
time_ns()

Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.

source
Base.ticFunction.
tic()

Set a timer to be read by the next call to toc or toq. The macro call @time expr can also be used to time evaluation.

julia> tic()
0x0000c45bc7abac95

julia> sleep(0.3)

julia> toc()
elapsed time: 0.302745944 seconds
0.302745944
source
Base.tocFunction.
toc()

Print and return the time elapsed since the last tic. The macro call @time expr can also be used to time evaluation.

julia> tic()
0x0000c45bc7abac95

julia> sleep(0.3)

julia> toc()
elapsed time: 0.302745944 seconds
0.302745944
source
Base.toqFunction.
toq()

Return, but do not print, the time elapsed since the last tic. The macro calls @timed expr and @elapsed expr also return evaluation time.

julia> tic()
0x0000c46477a9675d

julia> sleep(0.3)

julia> toq()
0.302251004
source
Base.@timeMacro.
@time

A macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

See also @timev, @timed, @elapsed, and @allocated.

julia> @time rand(10^6);
  0.001525 seconds (7 allocations: 7.630 MiB)

julia> @time begin
           sleep(0.3)
           1+1
       end
  0.301395 seconds (8 allocations: 336 bytes)
source
Base.@timevMacro.
@timev

This is a verbose version of the @time macro. It first prints the same information as @time, then any non-zero memory allocation counters, and then returns the value of the expression.

See also @time, @timed, @elapsed, and @allocated.

julia> @timev rand(10^6);
  0.001006 seconds (7 allocations: 7.630 MiB)
elapsed time (ns): 1005567
bytes allocated:   8000256
pool allocs:       6
malloc() calls:    1
source
Base.@timedMacro.
@timed

A macro to execute an expression, and return the value of the expression, elapsed time, total bytes allocated, garbage collection time, and an object with various memory allocation counters.

See also @time, @timev, @elapsed, and @allocated.

julia> val, t, bytes, gctime, memallocs = @timed rand(10^6);

julia> t
0.006634834

julia> bytes
8000256

julia> gctime
0.0055765

julia> fieldnames(typeof(memallocs))
9-element Array{Symbol,1}:
 :allocd
 :malloc
 :realloc
 :poolalloc
 :bigalloc
 :freecall
 :total_time
 :pause
 :full_sweep

julia> memallocs.total_time
5576500
source
Base.@elapsedMacro.
@elapsed

A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.

See also @time, @timev, @timed, and @allocated.

julia> @elapsed sleep(0.3)
0.301391426
source
Base.@allocatedMacro.
@allocated

A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression. Note: the expression is evaluated inside a local function, instead of the current context, in order to eliminate the effects of compilation, however, there still may be some allocations due to JIT compilation. This also makes the results inconsistent with the @time macros, which do not try to adjust for the effects of compilation.

See also @time, @timev, @timed, and @elapsed.

julia> @allocated rand(10^6)
8000080
source
Base.EnvHashType.
EnvHash() -> EnvHash

A singleton of this type provides a hash table interface to environment variables.

source
Base.ENVConstant.
ENV

Reference to the singleton EnvHash, providing a dictionary interface to system environment variables.

source
Base.is_unixFunction.
is_unix([os])

Predicate for testing if the OS provides a Unix-like interface. See documentation in Handling Operating System Variation.

source
Base.is_appleFunction.
is_apple([os])

Predicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. See documentation in Handling Operating System Variation.

source
Base.is_linuxFunction.
is_linux([os])

Predicate for testing if the OS is a derivative of Linux. See documentation in Handling Operating System Variation.

source
Base.is_bsdFunction.
is_bsd([os])

Predicate for testing if the OS is a derivative of BSD. See documentation in Handling Operating System Variation.

source
Base.is_windowsFunction.
is_windows([os])

Predicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation in Handling Operating System Variation.

source
Sys.windows_version()

Returns the version number for the Windows NT Kernel as a (major, minor) pair, or (0, 0) if this is not running on Windows.

source
Base.@staticMacro.
@static

Partially evaluates an expression at parse time.

For example, @static is_windows() ? foo : bar will evaluate is_windows() and insert either foo or bar into the expression. This is useful in cases where a construct would be invalid on other platforms, such as a ccall to a non-existent function. @static if is_apple() foo end and @static foo <&&,||> bar are also valid syntax.

source

Errors

Base.errorFunction.
error(message::AbstractString)

Raise an ErrorException with the given message.

source
Core.throwFunction.
throw(e)

Throw an object as an exception.

source
Base.rethrowFunction.
rethrow([e])

Throw an object without changing the current exception backtrace. The default argument is the current exception (if called within a catch block).

source
Base.backtraceFunction.
backtrace()

Get a backtrace object for the current program point.

source
Base.catch_backtraceFunction.
catch_backtrace()

Get the backtrace of the current exception, for use within catch blocks.

source
Base.assertFunction.
assert(cond)

Throw an AssertionError if cond is false. Also available as the macro @assert expr.

source
Base.@assertMacro.
@assert cond [text]

Throw an AssertionError if cond is false. Preferred syntax for writing assertions. Message text is optionally displayed upon assertion failure.

source
ArgumentError(msg)

The parameters to a function call do not match a valid signature. Argument msg is a descriptive error string.

source
AssertionError([msg])

The asserted condition did not evaluate to true. Optional argument msg is a descriptive error string.

source
BoundsError([a],[i])

An indexing operation into an array, a, tried to access an out-of-bounds element, i.

source
DimensionMismatch([msg])

The objects called do not have matching dimensionality. Optional argument msg is a descriptive error string.

source
DivideError()

Integer division was attempted with a denominator value of 0.

source
DomainError()

The arguments to a function or constructor are outside the valid domain.

source
Base.EOFErrorType.
EOFError()

No more data was available to read from a file or stream.

source
ErrorException(msg)

Generic error type. The error message, in the .msg field, may provide more specific details.

source
InexactError()

Type conversion cannot be done exactly.

source
InterruptException()

The process was stopped by a terminal interrupt (CTRL+C).

source
Base.KeyErrorType.
KeyError(key)

An indexing operation into an Associative (Dict) or Set like object tried to access or delete a non-existent element.

source
Base.LoadErrorType.
LoadError(file::AbstractString, line::Int, error)

An error occurred while includeing, requireing, or using a file. The error specifics should be available in the .error field.

source
MethodError(f, args)

A method with the required type signature does not exist in the given generic function. Alternatively, there is no unique most-specific method.

source
NullException()

An attempted access to a Nullable with no defined value.

source
OutOfMemoryError()

An operation allocated too much memory for either the system or the garbage collector to handle properly.

source
ReadOnlyMemoryError()

An operation tried to write to memory that is read-only.

source
OverflowError()

The result of an expression is too large for the specified type and will cause a wraparound.

source
Base.ParseErrorType.
ParseError(msg)

The expression passed to the parse function could not be interpreted as a valid Julia expression.

source
ProcessExitedException()

After a client Julia process has exited, further attempts to reference the dead child will throw this exception.

source
StackOverflowError()

The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.

source
SystemError(prefix::AbstractString, [errno::Int32])

A system call failed with an error code (in the errno global variable).

source
Core.TypeErrorType.
TypeError(func::Symbol, context::AbstractString, expected::Type, got)

A type assertion failure, or calling an intrinsic function with an incorrect argument type.

source
UndefRefError()

The item or field is not defined for the given object.

source
UndefVarError(var::Symbol)

A symbol in the current scope is not defined.

source
Base.InitErrorType.
InitError(mod::Symbol, error)

An error occurred when running a module's __init__ function. The actual error thrown is available in the .error field.

source
Base.retryFunction.
retry(f::Function;  delays=ExponentialBackOff(), check=nothing) -> Function

Returns an anonymous function that calls function f. If an exception arises, f is repeatedly called again, each time check returns true, after waiting the number of seconds specified in delays. check should input delays's current state and the Exception.

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, UVError))(io, 128; all=false)
source
ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)

A Float64 iterator of length n whose elements exponentially increase at a rate in the interval factor * (1 ± jitter). The first element is first_delay and all elements are clamped to max_delay.

source

Events

Base.TimerMethod.
Timer(callback::Function, delay, repeat=0)

Create a timer to call the given callback function. The callback is passed one argument, the timer object itself. The callback will be invoked after the specified initial delay, and then repeating with the given repeat interval. If repeat is 0, the timer is only triggered once. Times are in seconds. A timer is stopped and has its resources freed by calling close on it.

source
Base.TimerType.
Timer(delay, repeat=0)

Create a timer that wakes up tasks waiting for it (by calling wait on the timer object) at a specified interval. Times are in seconds. Waiting tasks are woken with an error when the timer is closed (by close. Use isopen to check whether a timer is still active.

source
AsyncCondition()

Create a async condition that wakes up tasks waiting for it (by calling wait on the object) when notified from C by a call to uv_async_send. Waiting tasks are woken with an error when the object is closed (by close. Use isopen to check whether it is still active.

source
AsyncCondition(callback::Function)

Create a async condition that calls the given callback function. The callback is passed one argument, the async condition object itself.

source

Reflection

Base.module_nameFunction.
module_name(m::Module) -> Symbol

Get the name of a Module as a Symbol.

julia> module_name(Base.LinAlg)
:LinAlg
source
Base.module_parentFunction.
module_parent(m::Module) -> Module

Get a module's enclosing Module. Main is its own parent, as is LastMain after workspace().

julia> module_parent(Main)
Main

julia> module_parent(Base.LinAlg.BLAS)
Base.LinAlg
source
Base.current_moduleFunction.
current_module() -> Module

Get the dynamically current Module, which is the Module code is currently being read from. In general, this is not the same as the module containing the call to this function.

source
Base.fullnameFunction.
fullname(m::Module)

Get the fully-qualified name of a module as a tuple of symbols. For example,

julia> fullname(Base.Pkg)
(:Base, :Pkg)

julia> fullname(Main)
()
source
Base.namesFunction.
names(x::Module, all::Bool=false, imported::Bool=false)

Get an array of the names exported by a Module, excluding deprecated names. If all is true, then the list also includes non-exported names defined in the module, deprecated names, and compiler-generated names. If imported is true, then names explicitly imported from other modules are also included.

As a special case, all names defined in Main are considered "exported", since it is not idiomatic to explicitly export names from Main.

source
Core.nfieldsFunction.
nfields(x::DataType) -> Int

Get the number of fields of a DataType.

source
Base.fieldnamesFunction.
fieldnames(x::DataType)

Get an array of the fields of a DataType.

julia> fieldnames(Hermitian)
2-element Array{Symbol,1}:
 :data
 :uplo
source
Base.fieldnameFunction.
fieldname(x::DataType, i::Integer)

Get the name of field i of a DataType.

julia> fieldname(SparseMatrixCSC,1)
:m

julia> fieldname(SparseMatrixCSC,5)
:nzval
source
Base.datatype_moduleFunction.
Base.datatype_module(t::DataType) -> Module

Determine the module containing the definition of a DataType.

source
Base.datatype_nameFunction.
Base.datatype_name(t) -> Symbol

Get the name of a (potentially UnionAll-wrapped) DataType (without its parent module) as a symbol.

source
Base.isconstFunction.
isconst([m::Module], s::Symbol) -> Bool

Determine whether a global is declared const in a given Module. The default Module argument is current_module().

source
Base.function_nameFunction.
Base.function_name(f::Function) -> Symbol

Get the name of a generic Function as a symbol, or :anonymous.

source
Base.function_module(f::Function) -> Module

Determine the module containing the (first) definition of a generic function.

source
Base.function_module(f::Function, types) -> Module

Determine the module containing a given definition of a generic function.

source
Base.functionlocMethod.
functionloc(f::Function, types)

Returns a tuple (filename,line) giving the location of a generic Function definition.

source
Base.functionlocMethod.
functionloc(m::Method)

Returns a tuple (filename,line) giving the location of a Method definition.

source
@functionloc

Applied to a function or macro call, it evaluates the arguments to the specified call, and returns a tuple (filename,line) giving the location for the method that would be called for those arguments. It calls out to the functionloc function.

source

Internals

Base.gcFunction.
gc()

Perform garbage collection. This should not generally be used.

source
Base.gc_enableFunction.
gc_enable(on::Bool)

Control whether garbage collection is enabled using a boolean argument (true for enabled, false for disabled). Returns previous GC state. Disabling garbage collection should be used only with extreme caution, as it can cause memory use to grow without bound.

source
Base.macroexpandFunction.
macroexpand(x)

Takes the expression x and returns an equivalent expression with all macros removed (expanded).

source
@macroexpand

Return equivalent expression with all macros removed (expanded).

There is a subtle difference between @macroexpand and macroexpand in that expansion takes place in different contexts. This is best seen in the following example:

julia> module M
           macro m()
               1
           end
           function f()
               (@macroexpand(@m), macroexpand(:(@m)))
           end
       end
M

julia> macro m()
           2
       end
@m (macro with 1 method)

julia> M.f()
(1, 2)

With @macroexpand the expression expands where @macroexpand appears in the code (module M in the example). With macroexpand the expression expands in the current module where the code was finally called (REPL in the example). Note that when calling macroexpand or @macroexpand directly from the REPL, both of these contexts coincide, hence there is no difference.

source
Base.expandFunction.
expand(x)

Takes the expression x and returns an equivalent expression in lowered form. See also code_lowered.

source
Base.code_loweredFunction.
code_lowered(f, types)

Returns an array of lowered ASTs for the methods matching the given generic function and type signature.

source
@code_lowered

Evaluates the arguments to the function or macro call, determines their types, and calls code_lowered on the resulting expression.

source
Base.code_typedFunction.
code_typed(f, types; optimize=true)

Returns an array of lowered and type-inferred ASTs for the methods matching the given generic function and type signature. The keyword argument optimize controls whether additional optimizations, such as inlining, are also applied.

source
Base.@code_typedMacro.
@code_typed

Evaluates the arguments to the function or macro call, determines their types, and calls code_typed on the resulting expression.

source
Base.code_warntypeFunction.
code_warntype([io::IO], f, types)

Prints lowered and type-inferred ASTs for the methods matching the given generic function and type signature to io which defaults to STDOUT. The ASTs are annotated in such a way as to cause "non-leaf" types to be emphasized (if color is available, displayed in red). This serves as a warning of potential type instability. Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. See @code_warntype for more information.

source
@code_warntype

Evaluates the arguments to the function or macro call, determines their types, and calls code_warntype on the resulting expression.

source
Base.code_llvmFunction.
code_llvm([io], f, types)

Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to io which defaults to STDOUT.

All metadata and dbg.* calls are removed from the printed bitcode. Use code_llvm_raw for the full IR.

source
Base.@code_llvmMacro.
@code_llvm

Evaluates the arguments to the function or macro call, determines their types, and calls code_llvm on the resulting expression.

source
Base.code_nativeFunction.
code_native([io], f, types, [syntax])

Prints the native assembly instructions generated for running the method matching the given generic function and type signature to io which defaults to STDOUT. Switch assembly syntax using syntax symbol parameter set to :att for AT&T syntax or :intel for Intel syntax. Output is AT&T syntax by default.

source
@code_native

Evaluates the arguments to the function or macro call, determines their types, and calls code_native on the resulting expression.

source
Base.precompileFunction.
precompile(f,args::Tuple{Vararg{Any}})

Compile the given function f for the argument tuple (of types) args, but do not execute it.

source