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:
- Except for functions in built-in modules (
Pkg,Collections,TestandProfile), all functions documented here are directly available for use in programs. - To use module functions, use
importModuleto import the module, andModule.fn(x)to use the functions. - Alternatively,
usingModulewill import all exportedModulefunctions into the current namespace. - By convention, function names ending with an exclamation point (
!) modify their arguments. Some functions have both modifying (e.g.,sort!) and non-modifying (sort) versions.
Getting Around¶
exit([code])¶Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.
quit()¶Quit the program indicating that the processes completed successfully. This function calls
exit(0)(seeexit()).
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.
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
fis the REPL object. This function should be called from within the.juliarc.jlinitialization file.
isinteractive() → Bool¶Determine whether Julia is running an interactive session.
whos([io,] [Module,] [pattern::Regex])¶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.
Base.summarysize(obj; exclude=Union{Module, Function, DataType, TypeName}) → Int¶Compute the amount of memory used by all unique objects reachable from the argument. Keyword argument
excludespecifies a type of objects to exclude from the traversal.
edit(path::AbstractString[, line])¶Edit a file or directory optionally providing a line number to edit the file at. Returns to the
juliaprompt when you quit the editor.
edit(function[, types])Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit.
@edit()¶Evaluates the arguments to the function or macro call, determines their types, and calls the
editfunction on the resulting expression.
less(file::AbstractString[, line])¶Show a file using the default pager, optionally providing a starting line number. Returns to the
juliaprompt when you quit the pager.
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.
@less()¶Evaluates the arguments to the function or macro call, determines their types, and calls the
lessfunction on the resulting expression.
clipboard(x)¶Send a printed form of
xto the operating system clipboard (“copy”).
clipboard() → AbstractStringReturn a string with the contents of the operating system clipboard (“paste”).
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.
require(module::Symbol)¶This function is part of the implementation of
using/import, if a module is not already defined inMain. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).Loads a source files, in the context of the
Mainmodule, on every active node, searching standard locations for files.requireis considered a top-level operation, so it sets the currentincludepath but does not use it to search for files (see help forinclude). This function is typically used to load library code, and is implicitly called byusingto load packages.When searching for files,
requirefirst looks for package code underPkg.dir(), then tries paths in the global arrayLOAD_PATH.requireis case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.
Base.compilecache(module::String)¶Creates a precompiled cache file for module (see help for
require) and all of its dependencies. This can be used to reduce package load times. Cache files are stored inLOAD_CACHE_PATH[1], which defaults to~/.julia/lib/VERSION. See Module initialization and precompilation for important notes.
__precompile__(isprecompilable::Bool=true)¶Specify whether the file calling this function is precompilable. If
isprecompilableistrue, then__precompile__throws an exception when the file is loaded byusing/import/requireunless 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 themoduledeclaration in the file, or better yetVERSION>=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.
include(path::AbstractString)¶Evaluate the contents of a source file in the current context. During including, a task-local include path is set to the directory containing the file. Nested calls to
includewill 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.
include_string(code::AbstractString[, filename])¶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.
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.
apropos(string)¶Search through all documentation for a string, ignoring case.
which(f, types)¶Returns the method of
f(aMethodobject) that would be called for arguments of the giventypes.If
typesis an abstract type, then the method that would be called byinvokeis returned.
which(symbol)Return the module in which the binding for the variable referenced by
symbolwas created.
@which()¶Applied to a function or macro call, it evaluates the arguments to the specified call, and returns the
Methodobject 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 thewhichfunction.
methods(f[, types])¶Returns the method table for
f.If
typesis specified, returns an array of methods whose types match.
methodswith(typ[, module or function][, showparents])¶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
showparentsistrue, also return arguments with a parent type oftyp, excluding typeAny.
@show()¶Show an expression and result, returning the result.
versioninfo([verbose::Bool])¶Print information about the version of Julia in use. If the
verboseargument istrue, detailed system information is shown as well.
workspace()¶Replace the top-level module (
Main) with a new one, providing a clean workspace. The previousMainmodule is made available asLastMain. A previously-loaded package can be accessed using a statement such asusingLastMain.Package.This function should only be used interactively.
ans¶A variable referring to the last computed value, automatically set at the interactive prompt.
All Objects¶
is(x, y) → Bool¶===(x, y) → Bool¶≡(x, y) → Bool¶Determine whether
xandyare 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 calledegal.
isa(x, type) → Bool¶Determine whether
xis of the giventype.
isequal(x, y)¶Similar to
==, except treats all floating-pointNaNvalues as equal to each other, and treats-0.0as unequal to0.0. The default implementation ofisequalcalls==, so if you have a type that doesn’t have these floating-point subtleties then you probably only need to define==.isequalis the comparison function used by hash tables (Dict).isequal(x,y)must imply thathash(x)==hash(y).This typically means that if you define your own
==function then you must define a correspondinghash(and vice versa). Collections typically implementisequalby callingisequalrecursively on all contents.Scalar types generally do not need to implement
isequalseparate from==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based onisnan,signbit, and==).
isless(x, y)¶Test whether
xis less thany, according to a canonical total order. Values that are normally unordered, such asNaN, are ordered in an arbitrary but consistent fashion. This is the default comparison used bysort. 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 asNaN.
ifelse(condition::Bool, x, y)¶Return
xifconditionistrue, otherwise returny. This differs from?orifin that it is an ordinary function, so all the arguments are evaluated first. In some cases, usingifelseinstead of anifstatement can eliminate the branch in generated code and provide higher performance in tight loops.
lexcmp(x, y)¶Compare
xandylexicographically and return -1, 0, or 1 depending on whetherxis less than, equal to, or greater thany, respectively. This function should be defined for lexicographically comparable types, andlexlesswill calllexcmpby default.
lexless(x, y)¶Determine whether
xis lexicographically less thany.
typeof(x)¶Get the concrete type of
x.
tuple(xs...)¶Construct a tuple of the given objects.
ntuple(f::Function, n)¶Create a tuple of length
n, computing each element asf(i), whereiis the index of the element.
object_id(x)¶Get a hash value for
xbased on object identity.object_id(x)==object_id(y)ifx===y.
hash(x[, h::UInt])¶Compute an integer hash code such that
isequal(x,y)implieshash(x)==hash(y). The optional second argumenthis a hash code to be mixed with the result.New types should implement the 2-argument form, typically by calling the 2-argument
hashmethod recursively in order to mix hashes of the contents with each other (and withh). Typically, any type that implementshashshould also implement its own==(henceisequal) to guarantee the property mentioned above.
finalizer(x, function)¶Register a function
f(x)to be called when there are no program-accessible references tox. The behavior of this function is unpredictable ifxis of a bits type.
finalize(x)¶Immediately run finalizers registered for object
x.
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.
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. Callingdeepcopyon 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
deepcopybehavior by defining a specialized version of the functiondeepcopy_internal(x::T,dict::ObjectIdDict)(which shouldn’t otherwise be used), whereTis the type to be specialized for, anddictkeeps track of objects copied so far within the recursion. Within the definition,deepcopy_internalshould be used in place ofdeepcopy, and thedictvariable should be updated as appropriate before returning.
isdefined([m::Module, ]s::Symbol)¶isdefined(object, s::Symbol)isdefined(object, index::Int)isdefined(a::Array, index::Int)Tests whether an assignable location is defined. The arguments can be a module and a symbol, a composite object and field name (as a symbol) or index, or an
Arrayand index. With a single symbol argument, tests whether a global variable with that name is defined incurrent_module().Note: For
AbstractArrays other thanArray,isdefinedtests whether the given field index is defined, not the given array index. To test whether an array index is defined, useisassigned().
convert(T, x)¶Convert
xto a value of typeT.If
Tis anIntegertype, anInexactErrorwill be raised ifxis not representable byT, for example ifxis not integer-valued, or is outside the range supported byT.julia>convert(Int,3.0)3julia>convert(Int,3.5)ERROR:InexactError()inconvert(::Type{Int64},::Float64)at./int.jl:239...
If
Tis aAbstractFloatorRationaltype, then it will return the closest value toxrepresentable byT.julia>x=1/30.3333333333333333julia>convert(Float32,x)0.33333334f0julia>convert(Rational{Int32},x)1//3julia>convert(Rational{Int64},x)6004799503160661//18014398509481984
If
Tis a collection type andxa collection, the result ofconvert(T,x)may aliasx.julia>x=Int[1,2,3];julia>y=convert(Vector{Int},x);julia>y===xtrue
Similarly, if
Tis a composite type andxa related instance, the result ofconvert(T,x)may alias part or all ofx.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===xtruejulia>z===xfalsejulia>z.colptr===x.colptrtrue
promote(xs...)¶Convert all arguments to their common promotion type (if any), and return them all (as a tuple).
oftype(x, y)¶Convert
yto the type ofx(convert(typeof(x),y)).
widen(x)¶If
xis 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). Otherwisexis converted towiden(typeof(x)).julia>widen(Int32)Int64julia>widen(1.5f0)1.5
identity(x)¶The identity function. Returns its argument.
Types¶
supertype(T::DataType)¶Return the supertype of DataType
T.
issubtype(type1, type2)¶Return
trueif and only if all values oftype1are also oftype2. Can also be written using the<:infix operator astype1<:type2.
<:(T1, T2)¶Subtype operator, equivalent to
issubtype(T1,T2).
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.
typemin(T)¶The lowest value representable by the given (real) numeric DataType
T.
typemax(T)¶The highest value representable by the given (real) numeric
DataType.
realmin(T)¶The smallest in absolute value non-subnormal value representable by the given floating-point DataType
T.
realmax(T)¶The highest finite value representable by the given floating-point DataType
T.
maxintfloat(T)¶The largest integer losslessly representable by the given floating-point DataType
T.
sizeof(T)¶Size, in bytes, of the canonical binary representation of the given DataType
T, if any.
eps(T)¶The distance between 1.0 and the next larger representable floating-point value of
DataTypeT. Only floating-point types are sensible arguments.
eps()The distance between 1.0 and the next larger representable floating-point value of
Float64.
eps(x)The distance between
xand the next larger representable floating-point value of the sameDataTypeasx.
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)returnsFloat64even though strictly, not allInt64values can be represented exactly asFloat64values.
promote_rule(type1, type2)¶Specifies what type should be used by
promotewhen given values of typestype1andtype2. This function should not be called directly, but should have definitions added to it for new types as appropriate.
getfield(value, name::Symbol)¶Extract a named field from a
valueof composite type. The syntaxa.bcallsgetfield(a,:b).
setfield!(value, name::Symbol, x)¶Assign
xto a named field invalueof composite type. The syntaxa.b=ccallssetfield!(a,:b,c).
fieldoffset(type, i)¶The byte offset of field
iof a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct type:julia>structinfo(T)=[(fieldoffset(T,i),fieldname(T,i),fieldtype(T,i))fori=1:nfields(T)];julia>structinfo(Base.Filesystem.StatStruct)12-elementArray{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)
fieldtype(T, name::Symbol | index::Int)¶Determine the declared type of a field (specified by name or index) in a composite DataType
T.
isimmutable(v)¶Return
trueiff valuevis immutable. See Immutable 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 ofDataTypeis mutable.
isbits(T)¶Return
trueifTis a “plain data” type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such asUInt8,Float64, andComplex{Float64}.julia>isbits(Complex{Float64})truejulia>isbits(Complex)false
isleaftype(T)¶Determine whether
Tis a concrete type that can have instances, meaning its only subtypes are itself andUnion{}(butTitself is notUnion{}).
typejoin(T, S)¶Compute a type that contains both
TandS.
typeintersect(T, S)¶Compute a type that contains the intersection of
TandS. Usually this will be the smallest such type or one close to it.
Val{c}()¶Create a “value type” out of
c, which must be anisbitsvalue. 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 implementationf(::Type{Val{false}}), without having to test the boolean value at runtime.
@enum EnumName EnumValue1[=x] EnumValue2[=y]Create an
Enumtype with nameEnumNameand enum member values ofEnumValue1andEnumValue2with optional assigned values ofxandy, respectively.EnumNamecan be used just like other types and enum member values as regular values, such asjulia>@enumFRUITapple=1orange=2kiwi=3julia>f(x::FRUIT)="I'm a FRUIT with value: $(Int(x))"f(genericfunction with1method)julia>f(apple)"I'm a FRUIT with value: 1"
instances(T::Type)¶Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see
@enum).
Generic Functions¶
method_exists(f, Tuple type) → Bool¶Determine whether the given generic function has a method matching the given
Tupleof argument types.julia>method_exists(length,Tuple{Array})true
applicable(f, args...) → Bool¶Determine whether the given generic function has a method applicable to the given arguments.
julia>function f(x,y)x+yend;julia>applicable(f,1)falsejulia>applicable(f,1,2)true
invoke(f, (types...), args...)¶Invoke a method for the given generic function matching the specified types (as a tuple), 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).
|>(x, f)¶Applies a function to the preceding argument. This allows for easy function chaining.
julia>[1:5;]|>x->x.^2|>sum|>inv0.01818181818181818
Syntax¶
eval([m::Module, ]expr::Expr)¶Evaluate an expression in the given module and return the result. Every
Module(except those defined withbaremodule) has its own 1-argument definition ofeval, which evaluates expressions in that module.
@eval()¶Evaluate an expression and return the value.
evalfile(path::AbstractString)¶Load the file using
include, evaluate all expressions, and return the value of the last one.
esc(e::ANY)¶Only valid in the context of an
Exprreturned 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.
gensym([tag])¶Generates a symbol which will not conflict with other variable names.
@gensym()¶Generates a gensym symbol for a variable. For example,
@gensymxyis transformed intox=gensym("x");y=gensym("y").
parse(str, start; greedy=true, raise=true)¶Parse the expression string and return an expression (which could later be passed to eval for execution).
startis the index of the first character to start parsing. Ifgreedyistrue(default),parsewill try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will returnExpr(:incomplete,"(errormessage)"). Ifraiseistrue(default), syntax errors other than incomplete expressions will raise an error. Ifraiseisfalse,parsewill return an expression that will raise an error upon evaluation.
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
raiseistrue(default), syntax errors will raise an error; otherwise,parsewill return an expression that will raise an error upon evaluation.
Nullables¶
Nullable(x)¶Wrap value
xin an object of typeNullable, which indicates whether a value is present.Nullable(x)yields a non-empty wrapper, andNullable{T}()yields an empty instance of a wrapper that might contain a value of typeT.
get(x::Nullable[, y])¶Attempt to access the value of
x. Returns the value if it is present; otherwise, returnsyif provided, or throws aNullExceptionif not.
isnull(x)¶Is the
Nullableobjectxnull, i.e. missing a value?
System¶
run(command)¶Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non-zero status.
spawn(command)¶Run a command object asynchronously, returning the resulting
Processobject.
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))
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.
process_running(p::Process)¶Determine whether a process is currently running.
process_exited(p::Process)¶Determine whether a process has exited.
kill(p::Process, signum=SIGTERM)¶Send a signal to a process. The default is to terminate the process.
Sys.set_process_title(title::AbstractString)¶Set the process title. No-op on some operating systems. (not exported)
Sys.get_process_title()¶Get the process title. On some systems, will always return empty string. (not exported)
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.
ignorestatus(command)¶Mark a command object so that running it will not throw an error if the result code is non-zero.
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.
Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide,env, dir)Construct a new
Cmdobject, representing an external program and arguments, fromcmd, while changing the settings of the optional keyword arguments:ignorestatus::Bool: Iftrue(defaults tofalse), then theCmdwill not throw an error if the return code is nonzero.detach::Bool: Iftrue(defaults tofalse), then theCmdwill be run in a new process group, allowing it to outlive thejuliaprocess and not have Ctrl-C passed to it.windows_verbatim::Bool: Iftrue(defaults tofalse), then on Windows theCmdwill 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=trueis useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.windows_hide::Bool: Iftrue(defaults tofalse), then on Windows no new console window is displayed when theCmdis executed. This has no effect if a console is already open or on non-Windows systems.env: Set environment variables to use when running theCmd.envis either a dictionary mapping strings to strings, an array of strings of the form"var=val", an array or tuple of"var"=>valpairs, ornothing. In order to modify (rather than replace) the existing environment, createenvbycopy(ENV)and then setenv["var"]=valas 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
cmdare used. Normally, to create aCmdobject in the first place, one uses backticks, e.g.Cmd(`echo "Hello world"`,ignorestatus=true,detach=false)
setenv(command, env; dir=working_dir)¶Set environment variables to use when running the given
command.envis either a dictionary mapping strings to strings, an array of strings of the form"var=val", or zero or more"var"=>valpair arguments. In order to modify (rather than replace) the existing environment, createenvbycopy(ENV)and then settingenv["var"]=valas desired, or usewithenv.The
dirkeyword argument can be used to specify a working directory for the command.
withenv(f::Function, kv::Pair...)¶Execute
f()in an environment that is temporarily modified (not replaced as insetenv) by zero or more"var"=>valargumentskv.withenvis generally used via thewithenv(kv...)do...endsyntax. A value ofnothingcan be used to temporarily unset an environment variable (if it is set). Whenwithenvreturns, the original environment has been restored.
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
pipelinecalls. 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 examplepipeline(a,b,c)is equivalent topipeline(pipeline(a,b),c). This provides a more concise way to specify multi-stage pipelines.Examples:
run(pipeline(`ls`,`grep xyz`))run(pipeline(`ls`,"out.txt"))run(pipeline("out.txt",`grep xyz`))
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.appendcontrols whether file output appends to the file. This is a more general version of the 2-argumentpipelinefunction.pipeline(from,to)is equivalent topipeline(from,stdout=to)whenfromis a command, and topipeline(to,stdin=from)whenfromis another kind of data source.Examples:
run(pipeline(`dothings`,stdout="out.txt",stderr="errs.txt"))run(pipeline(`update`,stdout="log.txt",append=true))
gethostname() → AbstractString¶Get the local machine’s host name.
getipaddr() → IPAddr¶Get the IP address of the local machine.
getpid() → Int32¶Get Julia’s process ID.
time()¶Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.
time_ns()¶Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.
tic()¶Set a timer to be read by the next call to
toc()ortoq(). The macro call@timeexprcan also be used to time evaluation.
toc()¶Print and return the time elapsed since the last
tic(). The macro call@timeexprcan also be used to time evaluation.
toq()¶Return, but do not print, the time elapsed since the last
tic(). The macro calls@timedexprand@elapsedexpralso return evaluation time.
@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().
@timev()¶This is a verbose version of the
@timemacro. 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().
@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().
@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().
@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
@timemacros, which do not try to adjust for the effects of compilation.See also
@time(),@timev(),@timed(), and@elapsed().
EnvHash() → EnvHash¶A singleton of this type provides a hash table interface to environment variables.
ENV¶Reference to the singleton
EnvHash, providing a dictionary interface to system environment variables.
is_unix([os])¶Predicate for testing if the OS provides a Unix-like interface. See documentation in Handling Operating System Variation.
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.
is_linux([os])¶Predicate for testing if the OS is a derivative of Linux. See documentation in Handling Operating System Variation.
is_bsd([os])¶Predicate for testing if the OS is a derivative of BSD. See documentation in Handling Operating System Variation.
is_windows([os])¶Predicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation in Handling Operating System Variation.
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.
@static()¶Partially evaluates an expression at parse time.
For example,
@staticis_windows()?foo:barwill evaluateis_windows()and insert eitherfooorbarinto the expression. This is useful in cases where a construct would be invalid on other platforms, such as accallto a non-existent function.
Errors¶
error(message::AbstractString)¶Raise an
ErrorExceptionwith the given message.
throw(e)¶Throw an object as an exception.
rethrow([e])¶Throw an object without changing the current exception backtrace. The default argument is the current exception (if called within a
catchblock).
backtrace()¶Get a backtrace object for the current program point.
catch_backtrace()¶Get the backtrace of the current exception, for use within
catchblocks.
assert(cond)¶Throw an
AssertionErrorifcondisfalse. Also available as the macro@assertexpr.
@assert cond [text]Throw an
AssertionErrorifcondisfalse. Preferred syntax for writing assertions. Messagetextis optionally displayed upon assertion failure.
ArgumentError(msg)¶The parameters to a function call do not match a valid signature. Argument
msgis a descriptive error string.
AssertionError([msg])¶The asserted condition did not evaluate to
true. Optional argumentmsgis a descriptive error string.
BoundsError([a][, i])¶An indexing operation into an array,
a, tried to access an out-of-bounds element,i.
DimensionMismatch([msg])¶The objects called do not have matching dimensionality. Optional argument
msgis a descriptive error string.
DivideError()¶Integer division was attempted with a denominator value of 0.
DomainError()¶The arguments to a function or constructor are outside the valid domain.
EOFError()¶No more data was available to read from a file or stream.
ErrorException(msg)¶Generic error type. The error message, in the
.msgfield, may provide more specific details.
InexactError()¶Type conversion cannot be done exactly.
InterruptException()¶The process was stopped by a terminal interrupt (CTRL+C).
KeyError(key)¶An indexing operation into an
Associative(Dict) orSetlike object tried to access or delete a non-existent element.
LoadError(file::AbstractString, line::Int, error)¶An error occurred while
includeing,requireing, orusinga file. The error specifics should be available in the.errorfield.
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.
NullException()¶An attempted access to a
Nullablewith no defined value.
OutOfMemoryError()¶An operation allocated too much memory for either the system or the garbage collector to handle properly.
ReadOnlyMemoryError()¶An operation tried to write to memory that is read-only.
OverflowError()¶The result of an expression is too large for the specified type and will cause a wraparound.
ParseError(msg)¶The expression passed to the
parsefunction could not be interpreted as a valid Julia expression.
ProcessExitedException()¶After a client Julia process has exited, further attempts to reference the dead child will throw this exception.
StackOverflowError()¶The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.
SystemError(prefix::AbstractString[, errno::Int32])¶A system call failed with an error code (in the
errnoglobal variable).
TypeError(func::Symbol, context::AbstractString, expected::Type, got)¶A type assertion failure, or calling an intrinsic function with an incorrect argument type.
UndefRefError()¶The item or field is not defined for the given object.
UndefVarError(var::Symbol)¶A symbol in the current scope is not defined.
InitError(mod::Symbol, error)¶An error occurred when running a module’s
__init__function. The actual error thrown is available in the.errorfield.
retry(f, [retry_on]; n=1, max_delay=10.0) → Function¶Returns a lambda that retries function
fup tontimes in the event of an exception. Ifretry_onis aTypethen retry only for exceptions of that type. Ifretry_onis a functiontest_error(::Exception)->Boolthen retry only if it is true.The first retry happens after a gap of 50 milliseconds or
max_delay, whichever is lower. Subsequently, the delays between retries are exponentially increased with a random factor up tomax_delay.Examples
retry(http_get,e->e.status=="503")(url)retry(read,UVError)(io)
Events¶
Timer(callback::Function, delay, repeat=0)¶Create a timer to call the given
callbackfunction. Thecallbackis passed one argument, the timer object itself. The callback will be invoked after the specified initialdelay, and then repeating with the givenrepeatinterval. Ifrepeatis0, the timer is only triggered once. Times are in seconds. A timer is stopped and has its resources freed by callingcloseon it.
Timer(delay, repeat=0)Create a timer that wakes up tasks waiting for it (by calling
waiton the timer object) at a specified interval. Times are in seconds. Waiting tasks are woken with an error when the timer is closed (byclose). Useisopento check whether a timer is still active.
AsyncCondition()¶Create a async condition that wakes up tasks waiting for it (by calling
waiton 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 (byclose). Useisopento check whether it is still active.
AsyncCondition(callback::Function)Create a async condition that calls the given
callbackfunction. Thecallbackis passed one argument, the async condition object itself.
Reflection¶
module_name(m::Module) → Symbol¶Get the name of a
Moduleas aSymbol.
module_parent(m::Module) → Module¶Get a module’s enclosing
Module.Mainis its own parent, as isLastMainafterworkspace().
current_module() → Module¶Get the dynamically current
Module, which is theModulecode is currently being read from. In general, this is not the same as the module containing the call to this function.
fullname(m::Module)¶Get the fully-qualified name of a module as a tuple of symbols. For example,
fullname(Base.Pkg)gives(:Base,:Pkg), andfullname(Main)gives().
names(x::Module[, all=false[, imported=false]])¶Get an array of the names exported by a
Module, with optionally moreModuleglobals according to the additional parameters.
nfields(x::DataType) → Int¶Get the number of fields of a
DataType.
fieldnames(x::DataType)¶Get an array of the fields of a
DataType.
fieldname(x::DataType, i)¶Get the name of field
iof aDataType.
Base.datatype_module(t::DataType) → Module¶Determine the module containing the definition of a
DataType.
isconst([m::Module, ]s::Symbol) → Bool¶Determine whether a global is declared
constin a givenModule. The defaultModuleargument iscurrent_module().
Base.function_name(f::Function) → Symbol¶Get the name of a generic
Functionas a symbol, or:anonymous.
Base.function_module(f::Function) → Module¶Determine the module containing the (first) definition of a generic function.
Base.function_module(f::Function, types) → ModuleDetermine the module containing a given definition of a generic function.
functionloc(f::Function, types)¶Returns a tuple
(filename,line)giving the location of a genericFunctiondefinition.
functionloc(m::Method)Returns a tuple
(filename,line)giving the location of aMethoddefinition.
@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 thefunctionlocfunction.
Internals¶
gc()¶Perform garbage collection. This should not generally be used.
gc_enable(on::Bool)¶Control whether garbage collection is enabled using a boolean argument (
truefor enabled,falsefor 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.
macroexpand(x)¶Takes the expression
xand returns an equivalent expression with all macros removed (expanded).
expand(x)¶Takes the expression
xand returns an equivalent expression in lowered form.
code_lowered(f, types)¶Returns an array of lowered ASTs for the methods matching the given generic function and type signature.
@code_lowered()¶Evaluates the arguments to the function or macro call, determines their types, and calls
code_lowered()on the resulting expression.
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
optimizecontrols whether additional optimizations, such as inlining, are also applied.
@code_typed()¶Evaluates the arguments to the function or macro call, determines their types, and calls
code_typed()on the resulting expression.
code_warntype([io, ]f, types)¶Prints lowered and type-inferred ASTs for the methods matching the given generic function and type signature to
iowhich defaults toSTDOUT. 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.
@code_warntype()¶Evaluates the arguments to the function or macro call, determines their types, and calls
code_warntype()on the resulting expression.
code_llvm([io, ]f, types)¶Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to
iowhich defaults toSTDOUT.All metadata and dbg.* calls are removed from the printed bitcode. Use code_llvm_raw for the full IR.
@code_llvm()¶Evaluates the arguments to the function or macro call, determines their types, and calls
code_llvm()on the resulting expression.
code_native([io, ]f, types)¶Prints the native assembly instructions generated for running the method matching the given generic function and type signature to
iowhich defaults toSTDOUT.
@code_native()¶Evaluates the arguments to the function or macro call, determines their types, and calls
code_native()on the resulting expression.
precompile(f, args::Tuple{Vararg{Any}})¶Compile the given function
ffor the argument tuple (of types)args, but do not execute it.