basilisp.core¶
- fn (*)[source]¶
- fn (* x)
- fn (* x y)
- fn (* x y & args)
Multiply the arguments. If no arguments given, returns 1.
- dynamic Var *basilisp-version*¶
The current Basilisp version as a vector of
[major, minor, revision]
.
- dynamic Var *command-line-args*¶
A vector of command line arguments if this process was started with command line arguments as by
basilisp run {file_or_code}
ornil
otherwise.Note that this value will differ from
sys.argv
since it will not include the command line arguments consumed by Basilisp’s own CLI.
- dynamic Var *compiler-options*¶
- dynamic Var *data-readers*[source]¶
Data readers map which will be merged in to the default data reader map used by the reader. Mappings should be qualified symbols to functions taking one argument. The function will receive an unevaluated data structure and must return some value to the reader.
- dynamic Var *default-reader-features*¶
The set of all currently supported reader features.
- dynamic Var *err*[source]¶
The current value of standard error used by Basilisp.
Note that binding a new value to this Var will not affect Python code (which generally respects
sys.stderr
), though all Basilisp code should respect the value.
- dynamic Var *flush-on-newline*[source]¶
Indicates whether the
prn
andprintln
functions should flush the output stream after the last newline is written.Defaults to
true
.
- dynamic Var *in*[source]¶
The current value of standard in used by Basilisp.
Note that binding a new value to this Var will not affect Python code (which generally respects
sys.stdin
), though all Basilisp code should respect the value.
- dynamic Var *main-ns*¶
The name of the main namespace as a symbol if this process was executed as
basilisp run -n {namespace}
orpython -m {namespace}
ornil
otherwise.This can be useful for detecting scripts similarly to how Python scripts use the idiom
if __name__ == "__main__":
.
- dynamic Var *ns*¶
Pointer to the current namespace.
This value is used by both the compiler and runtime to determine where newly defined Vars should be bound, so users should not alter or bind this Var unless they know what they’re doing.
- dynamic Var *out*[source]¶
The current value of standard out used by Basilisp.
Note that binding a new value to this Var will not affect Python code (which generally respects
sys.stdout
), though all Basilisp code should respect the value.
- dynamic Var *print-dup*¶
- dynamic Var *print-length*¶
- dynamic Var *print-level*¶
- dynamic Var *print-meta*¶
- dynamic Var *print-namespace-maps*¶
Indicates to print the namespace of keys in a map belonging to the same namespace, at the beginning of the map instead of beside the keys. Defaults to false.
- dynamic Var *print-readably*¶
- dynamic Var *python-version*¶
The current Python version as a vector of
[major, minor, revision]
.
- dynamic Var *resolver*[source]¶
Resolver used for resolving namespace aliases when reading forms using read, read-string, etc.
- fn (+)[source]¶
- fn (+ x)
- fn (+ x y)
- fn (+ x y & args)
Sum the arguments together. If no arguments given, returns 0.
- fn (- x)[source]¶
- fn (- x y)
- fn (- x y & args)
Subtract the arguments. If one argument given, returns the negation of that argument.
- macro (-> x & forms)[source]¶
Thread
x
through theforms
. Places x in the second position of the first form, and then the resulting expression into the second position of the second form, etc. Forms which are not lists will be made into lists.
- macro (->> x & forms)[source]¶
Thread
x
through theforms
. Placesx
in the last position of the first form, and then the resulting expression into the last position of the second form, etc. Forms which are not lists will be made into lists.
- fn (-collect-keyword-args kwargs)[source]¶
Implementation detail for associative destructuring of function keyword arguments.
Collect all keyword arguments into a single map. Support trailing map arguments which are joined into the final map.
- macro (.. x & method-calls)[source]¶
Expand into nested method calls on the returned objects from previous method calls.
Successive method invocations are represented as successive lists:
(.. "abc" (lower)) ;=> (. "abc" lower) (.. "abc" lower (split ",")) ;=> (. (. "abc" lower) split ",")
Methods invoked without arguments may be supplied as bare symbols.
- fn (/ x)[source]¶
- fn (/ x y)
- fn (/ x y & args)
Divide the arguments. If no arguments given, returns the inverse of the argument.
- fn (< _)[source]¶
- fn (< x & args)
Return
true
if arguments are monotonically increasing, otherwisefalse
.
- fn (= _)[source]¶
- fn (= x & args)
Return
true
ifx
andy
are equal, otherwisefalse
.Number equality follows Python’s
=
semantics whereby “a comparison between numbers of different types behaves as though the exact values of those numbers were being compared”.
- fn (> _)[source]¶
- fn (> x & args)
Return
true
if arguments are monotonically decreasing, otherwisefalse
.
- typeEduction¶
- typeEductionSeq¶
- fn (add-tap tf)[source]¶
- fn (add-tap topic tf)
Add
tf
, a function of one argument, to the tap set for the topictopic
. If no topic is given, the default topic is used.Tap functions are called only with values from calls to
tap>
with the topic they are added with.Taps may be removed from the tap set for a topic (or with the default topic) by a matching call to
remove-tap
. Taps are identified only by their identity, so hang on to a reference if you do need to remove the tap.Returns nil.
- fn (add-watch ref k wf)[source]¶
Add a watch function
wf
identified by the keyk
to the ref (Atom or Var).Watch functions should be functions of four arguments: the key associated with the watch function, the ref object, the old value, and the new value.
Watch functions will be called synchronously. Note that the value of a ref may have changed by the time a watch function is called, so watch functions should use the old and new state arguments rather than attempting to
deref
the ref.Watch functions cannot prevent state changes to a ref, regardless of the result of the watch function.
Watch function keys are used to identify watches and may be used to remove a watch from a ref (using
remove-watch
), but are otherwise unused by the watch feature.Watches for a Var are only notified for Var root changes, not thread-local bindings.
- fn (aget array idx)[source]¶
- fn (aget array idx & idxs)
Return the value of the Python list at the index (or indices).
- fn (alter-meta! o f & args)[source]¶
Atomically swap the metadata on reference
o
to the result of(apply f m args)
wherem
is the current metadata ofo
.f
should be free of side effects. References include atoms, namespaces, and vars.
- fn (alter-var-root v f & args)[source]¶
Atomically alter the Var root by calling
(apply f root args)
and setting the root as the result.
- macro (amap array idx ret expr)[source]¶
Map
expr
over the Python list array, returning a new Python list with the result.This macro initially binds the symbol named by
ret
to a clone ofarray
. On each iteration, the index (named byidx
) ofret
is set to the return value ofexpr
.
- fn (ancestors tag)[source]¶
- fn (ancestors h tag)
Return the set of all ancestors (parents and grandparents and so forth) of
tag
in hierarchyh
.tag
may be either a valid Python type or a namespace-qualified keyword or symbol. Iftag
is a Python type, ancestors include any relationships established via calls toderive
as well as any superclasses (as returned bysupers
). Iftag
is a namespace-qualified keyword, only relationships fromderive
are returned.h
must be a hierarchy returned bymake-hierarchy
. Ifh
is not supplied, the global hierarchy will be used.
- macro (and)[source]¶
- macro (and & args)
Evaluate the expressions from left to right. If all expressions are truthy, return the result of the final expression. Otherwise, returns the first falsey expression. Calling
and
with no arguments returnstrue
.
- fn (apply f & args)[source]¶
Apply function
f
to the arguments provided.The last argument must always be coercible to a Seq. Intermediate arguments are not modified.
- fn (apply-kw f & args)[source]¶
Apply function
f
to the arguments provided, passing the keys from the final argument (which must be a map) as Python keyword arguments tof
. Keywords and symbol keys will be converted to strings and munged to be legal Python identifiers to avoid errors.The last argument must always be coercible to a Mapping. Intermediate arguments are not modified.
- macro (apply-method o method & args)[source]¶
Apply arguments to a method call. Equivalent to
(apply (.-method o) args)
.
- macro (areduce array idx ret init expr)[source]¶
Reduce the Python list
array
byexpr
, returning the reduced expression.This macro initially binds the symbol named by
ret
toinit
. On each iteration,ret
is rebound to the return value ofexpr
.
- macro (as-> x name & forms)[source]¶
Bind
x
to name and thread it through theforms
, replacing instances ofname
in forms with the threaded expression.
- fn (aset array idx val)[source]¶
- fn (aset array idx idx2 & idxs)
Sets the value of the Python list at the index (or indices). Returns
val
.
- macro (assert expr)[source]¶
- macro (assert expr message)
Evaluate
expr
and if it returns logical false, throw anAssertionError
.This macro does not emit an assertion if the dynamic Var
*assert*
is set to a logical false value.
- fn (assoc m k v)[source]¶
- fn (assoc m k v & kvs)
Associate keys to values in associative data structure
m
. Ifm
isnil
, returns a new map with key-valueskvs
.
- fn (assoc! m k v)[source]¶
- fn (assoc! m k v & kvs)
Associate keys to values in the transient associative data structure
m
.
- fn (assoc-in m ks v)[source]¶
Associate value in a nested associative structure, with
ks
as a sequence of keys andv
as the new value. If no map exists for any key inks
, a new empty map will be created.
- fn (associative? x)[source]¶
Return
true
ifx
implementsbasilisp.lang.interfaces.IAssociative
.
- fn (atom v)[source]¶
- fn (atom v & kwargs)
Return an Atom containing
v
. The value of an Atom at any point in time may be returned by :lpy:fn`deref` ing it. The value of an atom may be reset usingreset!
and may be swapped usingswap!
. All operations on an atom occur atomically.
- fn (bigdec x)[source]¶
Coerce
x
to a Pythondecimal.Decimal
.
- fn (bigint x)[source]¶
Coerce
x
to an integer.Python’s builtin
int
type is arbitrary precision, so there is no difference betweenbigint
,biginteger
, and Python’s builtinint
.
- fn (biginteger x)[source]¶
Coerce
x
to an integer.Python’s builtin
int
type is arbitrary precision, so there is no difference betweenbigint
,biginteger
, and Python’s builtinint
.
- macro (binding bindings & body)[source]¶
Establish thread-local bindings for the vars given. The bindings are guaranteed to clear once execution passes outside the scope of this block.
- fn (boolean x)[source]¶
Coerce
x
to a boolean.Only
false
andnil
are logical false and will returnfalse
. All other values will returntrue
.
- fn (booleans x)[source]¶
Dummy cast to a Python list of booleans.
This function is provided for Clojure compatibility.
- macro (bound-fn & fn-tail)[source]¶
Return a function with the same function tail (everything after
fn
when defining a function) which will be executed with the same thread-local Var bindings as were in effect whenbound-fn
was called.Returns the return value of the defined function.
This is primarily useful for creating functions which might need to run on a different thread, but which should have the same Var bindings in place as when it was defined.
- fn (bound-fn* f)[source]¶
Return a function which executes
f
with the same thread-local Var bindings as were in effect whenbound-fn*
was called.f
will be called with the same arguments as the returned function.Returns the return value of
f
.This is primarily useful for creating functions which might need to run on a different thread, but which should have the same Var bindings in place as when it was defined.
- fn (bounded-count n coll)[source]¶
Return the count (as by
count
) of anycoll
for whichcounted?
returnstrue
, otherwise return the lesser ofn
and the length ofcoll
.
- fn (byte-string x)[source]¶
- fn (byte-string x encoding)
- fn (byte-string x encoding errors)
Coerce
x
to a byte string (Pythonbytes
object).Arguments shall be interpreted exactly as with that object’s constructor.
- fn (byte-string? x)[source]¶
Return
true
ifx
is a byte string (the Pythonbytes
type).Note that Python supplies byte string and byte array objects in its standard library. To check if an object is a Python
bytearray
, usebytes?
.
- fn (bytes x)[source]¶
Dummy cast to a Python list of bytes (distinct from Python’s
bytarray
andbytes
types).This function is provided for Clojure compatibility.
- fn (bytes? x)[source]¶
Return
true
ifx
is a byte array (the Pythonbytearray
type).Note that Python supplies byte string and byte array objects in its standard library. This function complies with Clojure’s standard library in returning true iff
x
is a Pythonbytearray
. To check if an object is a Pythonbytes
, usebyte-string?
.
- macro (case expr & clauses)[source]¶
Switch on
expr
to return a matching clause from the set of input clauses.The input expression may be any valid Basilisp expression. A single default expression can follow the clauses, and its value will be returned if no clause matches.
The clauses are pairs of a matching value and a return value. The matching values are not evaluated and must be compile-time constants. Symbols will not be resolved. Lists may be passed to match multiple compile time values to a single return value. The dispatch is done in constant time.
- fn (char x)[source]¶
Coerce
x
to a string of length 1.Natural integers are treated as ordinals and passed to Python’s
chr()
. Strings of length 1 are returned as such. Other types will result in aValueError
.
- fn (chars x)[source]¶
Dummy cast to a Python list of chars.
This function is provided for Clojure compatibility.
- fn (coll? x)[source]¶
Return
true
ifx
implementsbasilisp.lang.interfaces.IPersistentCollection
.
- fn (comp)[source]¶
- fn (comp f)
- fn (comp f g)
- fn (comp f g & args)
Return a function which is the composition of all the functions given as arguments. Note that, as in mathematical function composition, the argument functions are called from right to left.
- fn (compare x y)[source]¶
Return either -1, 0, or 1 to indicate the relationship between
x
andy
.This is a 3-way comparator commonly used in Java-derived systems. Python does not typically use 3-way comparators, so this function convert’s Python’s
__lt__
and__gt__
method returns into one of the 3-way comparator return values.Comparisons are generally only valid between homogeneous objects, with the exception of numbers which can be compared regardless of type. Most scalar value types (including
nil
, booleans, numbers, strings, keywords, and symbols) are comparable.nil
compares less than all values except itself.NaN
compares equal to all numbers, including itself. Strings are compared lexicographically. Symbols and keywords are sorted first on their namespace, if they have one, and then on their name. Symbols and keywords with namespaces always sort ahead of those without. Symbols cannot be compared to keywords.Of the built in collection types, only vectors can be compared. Vectors are compared first by their length and then element-wise.
Other collections such as maps, sequences, and sets cannot be compared.
Python objects supporting
__lt__
and__gt__
can generally be compared.
- fn (compare-and-set! atom old-val new-val)[source]¶
Atomically set the value of
atom
tonew-val
if and only ifold-val
is the current value of the atom.
- fn (complement f)[source]¶
Return a function which returns the logical complement of the return value of
(apply f args)
.
- fn (completing f)[source]¶
- fn (completing f cf)
Given a reducing function of two arguments,
f
, return a function with both 0-, 1-, and 2-arities appropriate fortransduce
. The 0-arity will return a call tof
with no arguments. The 1-arity will callcf
on its argument. The 2-arity will callf
directly with both of its arguments.If
cf
is not given,identity
will be used.
- macro (cond & clauses)[source]¶
Given groups of test/expression pairs, evaluate each test and, if
true
, return the expression. Otherwise, continue through until reaching the final expression.
- macro (cond-> x & clauses)[source]¶
Takes a test and form pair, threading
x
(as by->
) through each form for which the corresponding test evaluates astrue
.cond->
does not short circuit evaluation in any case.
- macro (cond->> x & clauses)[source]¶
Takes a test and form pair, threading
x
(as by->>
) through each form for which the corresponding test evaluates astrue
.cond->>
does not short circuit evaluation in any case.
- macro (condp pred expr & clauses)[source]¶
Take a predicate and an expression and a series of clauses, call
(pred test expr)
on the first expression for each clause. The result expression from first the set of clauses for which this expression returns a truthy value will be returned from thecondp
expression.Clauses can take two forms:
test-expr result-expr
test-expr :>> result-fn
where :>> is a keyword literal
For the ternary expression clause, the unary
result-fn
will be called with the result of the predicate.
- fn (conj)[source]¶
- fn (conj coll)
- fn (conj coll x)
- fn (conj coll x & xs)
Conjoin
xs
to collectioncoll
. New elements may be added in different positions depending on the type ofcoll
.conj
returns the same type ascoll
. Ifcoll
isnil
, return a list withxs
conjoined.
- fn (conj!)[source]¶
- fn (conj! coll)
- fn (conj! coll & xs)
Conjoin
xs
to the transient collection`coll
. New elements may be added in different positions depending on the type ofcoll
.conj!
returns the same type ascoll
.
- fn (cons o seq)[source]¶
Creates a new sequence where
o
is the first element andseq
is the rest. Ifseq
is nil, return a list containingo
. Ifseq
is not a Seq, attempt to coerce it to a Seq and then conso
onto the resulting sequence.
- fn (contains? coll k)[source]¶
Return
true
ifcoll
containsk
. For vectors,k
is an index. For maps,k
is a key. For sets,k
is a value in the set.
- fn (count coll)[source]¶
Return the length of
coll
as by Python’slen
builtin, or 0 ifcoll
is nil. If the collection does not respond to__len__
, then count it manually.
- fn (create-ns ns-sym)[source]¶
Create a Namespace with the name
ns-sym
or return the existing one if it already exists.
- fn (decimal? x)[source]¶
Return
true
ifx
is adecimal.Decimal
.
- macro (declare & names)[source]¶
Declare the given
names
as Vars with no bindings, as a forward declaration.
- fn (dedupe)[source]¶
- fn (dedupe coll)
Return a lazy sequence of the elements of
coll
, removing consecutive duplicates.Return a stateful transducer if no collection is provided.
- macro (defasync name & body)[source]¶
Define a new asynchronous function as by
defn
.Asynchronous functions are compiled as Python
async def
s.
- Var default-data-readers[source]¶
The default data readers used in reader macros. Overriding or attempting to change the root binding of this var will not change the default data readers.
- macro (definterface interface-name & methods)[source]¶
Define a new Python interface (abstract base clase) with the given name and method signatures.
Method signatures are in the form
(method-name [arg1 arg2 ...])
.self
orthis
arguments must be omitted from all interfaces.Interface objects cannot be directly instantiated. Instead, you must create a concrete implementation of an interface (perhaps via
deftype
) and supply implementations for all of the abstract methods.The generated interface derives from Python’s
abc.ABC
and all method definitions are declared asabc.abstractmethod()
s and thus must be implemented by a concrete type.Interfaces created by
definterface
cannot be declared as properties, class methods, or static methods, as withdeftype
.
- macro (defmacro body)[source]¶
- macro (defmacro & body)
- macro (defmacro attr-map? & body)
Define a new macro function. The arguments and syntax of
defmacro
are identical to that ofdefn
.When the compiler encounters a new macro function invocation, it immediately invokes that function during compilation and substitutes the function invocation with the return value of the called macro. Macros must return valid syntax at the point they are invoked, otherwise the compiler will throw an exception and compilation will halt.
Macros created by
defmacro
have access to two implicit arguments whose names must not appear in your argument list:&env
is a map of all symbol bindings available to the compiler at the point the macro is invoked.&form
is the original form invoking the macro. This is often useful for reading and copying metadata attached to the original form.
- macro (defmethod multifn dispatch-val & fn-tail)[source]¶
Add a new method to the multimethod
multifn
which responds todispatch-val
.fn-tail
is the trailing part of a function definition afterfn
including any relevant argument vectors.Methods added to a multimethod can be removed using
remove-method
. All methods may be removed usingremove-all-methods
.See
defmulti
for more information about multimethods.
- macro (defmulti name & body)[source]¶
Define a new multimethod with the given
name
and abody
consisting of an optional docstring, optional metadata map, a dispatch function and options of key/value pairs.Multimethod dispatch functions should be defined with the same arity or arities as the registered methods. The provided dispatch function will be called first on all calls to the multimethod and should return a dispatch value which will be used to identify a registered method. If the value returned by the dispatch function does not correspond to a registered method, the method registered with the default dispatch value, if one is registered, will be called instead. Methods can be registered with the
defmethod
macro.Multimethods select a dispatch method by using
isa?
on all available dispatch values. Callers can provide a hierarchy to use forisa?
resolution. For cases where multiple dispatch values are registered which may return true for a call toisa?
callers must select preferred values usingprefer-method
or aRuntimeException
will be thrown when a unique method cannot be selected. Callers can view multimethod preferences by callingprefers
.Callers may specify options as key/value pairs after the dispatch function. Options include:
- keyword
:default
: the default value to use if no matching method is found for the selected dispatch value; the default value is
:default
- keyword
:hierarchy
: the default hierarchy to use for resolving
isa?
relationships; the default value is the global hierarchy; hierarchies should be passed as reference types (e.g. as aVar
)
Multimethods are useful for defining polymorphic functions based on characteristics of their arguments. This behavior is often called multiple dispatch. Unlike typical multiple dispatch implementations, however, it is possible to define multimethods which dispatch on characteristics other than the types of input values (though you may define multimethods which dispatch solely on the types of arguments).
For cases where you might want to define a polymorphic function or functions based solely on the type of the first argument, you should consider defining a protocol (via
defprotocol
) instead. Protocols should generally perform better in cases where the primary goal is dispatching on the type of the first argument.- keyword
- macro (defn body)[source]¶
- macro (defn & body)
- macro (defn attr-map? & body)
Define a new function with an optional docstring.
The function will be interned in the current Namespace as a Var using the given
name
.After the name, an optional mapping of meta attributes may be provided. Any metadata values given will be attached to the metadata of the interned Var. A few special meta keys change how
defn
emits the final Var and function::decorators
is an optional vector of functions which will wrap the final function emitted bydefn
. Like standard Python decorators and thecomp
function, decorators are applied to the generated function from right to left.
Specify an optional docstring after the metadata map to provide callers with additional details about your function, its arguments, and its return value. If a docstring is provided, it will be attached to the interned Var metadata under the :doc key.
Functions may be defined with 1 or more arities. Functions of a single arity may be defined with a single vector of 0 or more arguments after the optional metadata map. Any forms appearing after the argument vector will be part of the function body. It is legal to define a function with no body. In this case, your function will always return
nil
.Functions with multiple arities are defined as a series of lists after the optional metadata map. Each list must contain an argument vector and 0 or more body forms. No arity may share the same number of fixed (non-variadic) arguments. There may be at most one variadic arity defined per function and the number of fixed arguments to that arity must be greater than or equal than the number of fixed arguments of all other arities.
- macro (defn- name & body)[source]¶
Define a new private function as by
defn
.Private functions are
def
‘ed with the:private
metadata, which makes them ineligible for access outside the namespace usingrequire
orrefer
.
- macro (defonce name expr)[source]¶
Define the Var named by
name
with root binding set toexpr
if and only if aname
is not already defined as a Var in this namespace.expr
will not be evaluated if the Var already exists.
- macro (defprotocol protocol-name & methods)[source]¶
Define a new protocol.
Protocols are similar to classical programming interfaces. Rather than defining an interface and implementing that interface on different objects, protocols generate a set of functions which dispatch to the correct implementation on the type of their first argument (which is similar to the Python
self
argument).Also like interfaces, Protocols do not include implementations for any of their member methods. Instead, implementations can be provided using
deftype
,defrecord
,reify
, orextend
(or any of theextend-*
macros).Despite their differences from interfaces, Protocols do also generate a standard Python interface type (deriving from
abc.ABC
) which is used for efficient dispatch for implementing types.Method signatures are in the form:
(method-name [self arg1] [self arg1 arg2] "This method foos the bars.")
Callers must provide the
self
orthis
arguments for each method.
- macro (defrecord type-name fields & method-impls)[source]¶
Define a new Basilisp record.
The new record will have fields matching the names in
fields
. Fields may be referred to unqualified in the bodies of implemented methods.Interface or protocol implementations are declared as the name of the interface or protocol as a symbol, followed by 1 or more method definitions for that interface. Types are not required to declare any interface implementations. Types which do declare interface implementations are required to implement all interface methods. Failing to implement all interface methods is a compile time error. Types implementing
object
are not required to implement allobject
methods.Method declarations should appear as:
(method-name [arg1] & body) (method-name [arg1 arg2 ...] & body)
Records objects are created with sensible
object
defaults as byattrs
. New records may overrideobject
defaults. An__init__
function is automatically created which takes positional arguments matching the order of definition infields
. Additionally, given a nameNewRecord
, a factory function will be created->NewRecord
which can be used to generate new instances of the record.Methods must supply a
this
orself
parameter.recur
special forms used in the body of a method should not include that parameter, as it will be supplied automatically.
- macro (deftype type-name fields & method-impls)[source]¶
Define a new Python concrete type which can implement 0 or more Python interfaces or Basilisp protocols.
The new type will have fields matching the names in
fields
. Fields may be referred to unqualified in the bodies of implemented methods. By default the fields of this type are immutable. Attempting to set non-mutable fields from a method body will result in a compiler error.Fields may be made mutable by annotating their definition with
:mutable
metadata. Mutable fields may be set within method bodies using theset!
special form. It is not advised to use mutable fields unless you are sure you know what you are doing. As a consequence of Python’s lax policy towards immutability, types with even one mutable field may be mutated by outside callers usingset!
, so bear that in mind when choosing mutability.Interface or protocol implementations are declared as the name of the interface or protocol as a symbol, followed by 1 or more method definitions for that interface. Types are not required to declare any interface implementations. Types which do declare interface implementations are required to implement all interface methods. Failing to implement all interface methods is a compile time error. Types implementing
object
are not required to implement allobject
methods.Method declarations should appear as:
(method-name [arg1] & body) (method-name [arg1 arg2 ...] & body)
Unlike in Clojure, interface and protocol methods are permitted to include variadic arguments. Single-arity methods may also declare support for keyword arguments using either the
:apply
or:collect
strategy on the:kwargs
metadata on the method name. Methods may be declared as static (using the:staticmethod
meta key) or class methods (using the:classmethod
meta key). Both static methods and class methods can be declared with multiple arities or may be defined with a single arity and keyword arguments. Finally, single-arity methods may be declared as Python properties using the:property
metadata on the method name. These facilities are provided as a means to interoperate with Python code and their use is discouraged in pure Basilisp code.Type objects are created with sensible
object
defaults as byattrs
. New types may overrideobject
defaults. An__init__
function is automatically created which takes positional arguments matching the order of definition infields
. Additionally, given a nameNewType
, a factory function will be created->NewType
which can be used to generate new instances of the type.Methods must supply a
this
orself
parameter.recur
special forms used in the body of a method should not include that parameter, as it will be supplied automatically.
- macro (delay & body)[source]¶
Takes a body of expressions producing any value. Will not produce a value until
deref
ed. The result is cached and returned in futurederefs
.
- fn (deliver p v)[source]¶
Deliver the value
v
to the promisep
. Ifp
already has a value, then a subsequent call todeliver
forp
will have no effect.
- fn (deref o)[source]¶
- fn (deref o timeout-s timeout-val)
Dereference a delay, atom, promise, future, volatile, or Var and returns its contents.
If
o
is an object implementingbasilisp.lang.interfaces.IBlockingDeref
andtimeout-s
andtimeout-val
are supplied,deref
will wait at mosttimeout-s
seconds, returningtimeout-val
iftimeout-s
seconds elapse ando
has not returned.
- fn (derive tag parent)[source]¶
- fn (derive h tag parent)
Derive a parent/child relationship between
tag
andparent
.tag
may be either a valid Python type or a namespace-qualified keyword or symbol.parent
must be a namespace-qualified keyword or symbol.h
must be a hierarchy returned bymake-hierarchy
. Ifh
is not supplied, the global hierarchy will be used.Relationships may be removed via
underive
.
- fn (descendants tag)[source]¶
- fn (descendants h tag)
Return the set of all descendants (children and grandchildren and so forth) of
tag
in hierarchyh
.tag
must be a namespace-qualified keyword or symbol. Python types are not supported fordescendants
checks.h
must be a hierarchy returned bymake-hierarchy
. Ifh
is not supplied, the global hierarchy will be used.
- fn (destructure [binding expr])[source]¶
Take a
[binding expr]
pair (as from alet
block) and produce all of the replacement bindings for the binding which perform destructuring on the initial expression.As an example, for sequential destructuring like:
[f & r :as v] [1 2 3 4]
This function would emit a list of bindings which can be inserted directly into a
let*
binding to perform destructuring:(v [1 2 3 4] f (nth v 0) r (nthnext v 1))
- fn (disj s)[source]¶
- fn (disj s elem)
- fn (disj s elem & elems)
Return a new version of the set
s
without the given elements. If the elements don’t exist ins
, they are ignored.
- fn (disj! s)[source]¶
- fn (disj! s elem)
- fn (disj! s elem & elems)
Return a new version of the transient set
s
without the given elements. If the elements don’t exist ins
, they are ignored.
- fn (dissoc m)[source]¶
- fn (dissoc m k)
- fn (dissoc m k & ks)
Return a new version of
m
without the given keys. If the keys don’t exist inm
, they are ignored.
- fn (dissoc! m k)[source]¶
- fn (dissoc! m k & ks)
Return a new version of the transient associative collection
m
without the given keys. If the keys don’t exist inm
, they are ignored.
- fn (distinct)[source]¶
- fn (distinct coll)
Return a lazy sequence of the elements of
coll
, removing duplicates.Return a stateful transducer if no collection is provided.
- fn (doall coll)[source]¶
- fn (doall n coll)
Force a lazy sequence be fully realized. Returns the head of the sequence.
This is often useful when you have a lazy sequence whose function also performs side effects.
Realizing an entire lazy sequence will force that sequence to exist fully in memory.
- fn (dorun coll)[source]¶
- fn (dorun n coll)
Force a lazy sequence be fully realized. Returns
nil
.This is often useful when you have a lazy sequence whose function also performs side effects.
Realizing an entire lazy sequence will force that sequence to exist fully in memory.
- macro (doseq bindings & body)[source]¶
Repeatedly run the body (likely for side effects) with bindings as described in the
for
macro. Returnsnil
.
- macro (dotimes binding & body)[source]¶
Repeatedly execute
body
(likely for side effects) while the binding name is repeatedly rebound from 0 to the binding value,n
, minus 1. Returnsnil
.
- macro (doto x & forms)[source]¶
Evaluate
x
and thread it as the first argument in all of the givenforms
. Returnsx
.Useful for creating a Python class and calling methods on it for initialization before returning the class.
- fn (double x)[source]¶
Coerce
x
to a float.Python does not differentiate between
float
anddouble
. Pythonfloat
s are double precision.
- fn (double? & args)[source]¶
Return
true
ifo
is afloat
.Same as
float?
. Python does not distinguish between single and double precision floating point numbers, so all floating points are calledfloat
and are double precision.
- fn (doubles x)[source]¶
Dummy cast to a Python list of doubles.
This function is provided for Clojure compatibility.
- fn (drop n)[source]¶
- fn (drop n coll)
Drop the first
n
elements ofcoll
.Return a stateful transducer if no collection is provided.
- fn (drop-while pred)[source]¶
- fn (drop-while pred coll)
Drop elements of
coll
until(pred elem)
returnstrue
.Return a stateful transducer if no collection is provided.
- fn (eduction & args)[source]¶
Return an iterable which is the application of the transducers
xform*
to the input collectioncoll
. Transducers will be applied tocomp
in the given order.Unlike with
sequence
,eduction
returns an iterable type which does not cache its results. As such, any computation will be performed again on each iteration.Eductions are likely to be more efficient in contexts where you would plan to consume the entire input collection and only plan to use that computation once. For cases with an infinite input sequence or if you need caching,
sequence
is preferred.
- fn (empty? coll)[source]¶
Return
true
ifcoll
is empty (as by(not (seq coll))
).Typically, you should prefer the idiom
(seq coll)
to(not (empty? coll))
.
- fn (ensure-reduced x)[source]¶
If
x
is not a reduced value, wrap it (as byreduced
) and return the wrapper. Otherwise returnx
.
- fn (eval form)[source]¶
- fn (eval form namespace)
Evaluate a form (not a string) and return its result.
If
namespace
is given, evaluate code in that Namespace. Otherwise, the current value of*ns*
is used.
- fn (every-pred pred)[source]¶
- fn (every-pred pred & preds)
Return a predicate composed of all of the input predicates, which returns
true
if all input predicates returntrue
for a value, otherwise returnsfalse
. The returned predicate returnsfalse
on the first failing predicate and will not execute any remaining predicates.
- fn (ex-cause ex)[source]¶
Return the cause (another Exception) of
ex
if it derives fromException
, otherwise it returnsnil
.
- fn (ex-data ex)[source]¶
Return the data map of
ex
if is an instance ofbasilisp.lang.interfaces.IExceptionInfo
, otherwise it returnsnil
.
- fn (ex-info msg data)[source]¶
Returns a
basilisp.lang.exception/ExceptionInfo
instance with the given message and data.
- fn (extend target-type & proto+methods)[source]¶
Extend a type dynamically with one or Protocol implementations. This is useful for types which were defined outside your control or which were not otherwise defined as direct implementors of the named Protocol(s). With
extend
, such types may be extended without modifying the types directly.target-type
should name a type which is to be extended. Virtually any type is permitted, so long as that that type is not also a Protocol. Iftarget-type
is an interface, objects of types implementing that interface will be extended by the given implementation unless a more concrete implementation is available (by the Python method resolution order of the object’s type). Iftarget-type` is ``nil
, it will be interpreted as(python/type nil)
.proto+methods
are interleaved Protocol names and maps of Protocol method implementations intended fortarget-type
. The keys of each map are keywords corresponding to the names of the Protocol methods (as defined in thedefprotocol
). Each value should be either an existing function (referenced by its Var or name binding) or a new function definition.extend
may be called multiple times for a singletarget-type
, so not all implementations need to be known a priori. Successive calls toextend
ontarget-type
with the same Protocol implementations will overwrite previous implementations.If you are extending types with explicit function definitions, the
extend-protocol
andextend-type
macros offer some additional conveniences.Returns
nil
.Example:
(extend SomeType FirstProto {:spam spam-fn :eggs (fn [...] ...)} OtherProto {:ham (fn [...] ...)})
- macro (extend-protocol proto & specs)[source]¶
Extend a Protocol with implementations for multiple types.
This convenience macro is useful for extending multiple different types with a single Protocol definition in one call. Note that this macro only supports new function declarations. If you intend to reference an existing function, call
extend
directly.For example, this call:
(extend-protocol SomeProto FirstType (spam ([this] ...) ([this arg] ...)) (eggs [this arg1 arg2] ...) OtherType (spam ([this] ...) ([this arg] ...)) (eggs [this arg1 arg2] ...))
Would be turned into the following
extend
calls:(do (extend FirstType SomeProto {:spam (fn spam ([this] ...) ([this arg] ...)) :eggs (fn [this arg1 arg2] ...)}) (extend OtherType SomeProto {:spam (fn spam ([this] ...) ([this arg] ...)) :eggs (fn [this arg1 arg2] ...)}))
- macro (extend-type target-type & specs)[source]¶
Extend a type with multiple Protocol implementations.
This convenience macro is useful for extending a single type with multiple different Protocol definitions in one call. Note that this macro only supports new function declarations. If you intend to reference an existing function, call
extend
directly.For example, this call:
(extend-type SomeType FirstProto (spam ([this] ...) ([this arg] ...)) (eggs [this arg1 arg2] ...) SecondProto (ham [this & args] ...))
Would be turned into the following
extend
call:(extend SomeType FirstProto {:spam (fn spam ([this] ...) ([this arg] ...)) :eggs (fn eggs [this arg1 arg2] ...)} SecondProto {:ham (fn ham [this & args] ...)})
- fn (extenders {:as proto :keys [impls]})[source]¶
Return a collection of types explicitly extending protocol
proto
.The returned collection will not include types which extend proto via inheritance (as by
deftype
and :lpy:fn`defrecord`). Only types extending proto viaextend
(orextend-protocol
orextend-type
) will appear.
- fn (extends? {:as proto :keys [interface impls]} type)[source]¶
Return
true
if
type extends protocolproto
.
- fn (file-seq dir)[source]¶
Return a seq of
pathlib.Path
objects for all files and subdirectories ofdir
.
- fn (filter pred)[source]¶
- fn (filter pred coll)
Return a lazy sequence of elements from
coll
where(pred elem)
returns a truthy value.Return a transducer if no collection is provided.
- fn (filterv & args)[source]¶
Return a vector of elements from
coll
where(pred elem)
returns a truthy value.
- fn (find-var sym)[source]¶
Return the Var named by namespace-qualified
sym
if it exists, ornil
otherwise.
- fn (first seq)[source]¶
If
seq
is a Seq, return the first element fromseq
. Ifseq
isnil
, returnnil
. Otherwise, coercesseq
to a Seq and returns the first element.
- fn (flatten v)[source]¶
Flatten any combination of nested sequences (such as lists or vectors) into a single lazy sequence. Calling
flatten
on non-sequential values returns an empty sequence.
- fn (floats x)[source]¶
Dummy cast to a Python list of floats.
This function is provided for Clojure compatibility.
- macro (fn & body)[source]¶
Return an anonymous (but possibly named) function.
Function argument vectors support sequential and associative Destructuring .
See
fn
for more details.
- macro (for bindings & body)[source]¶
Produce a list comprehension from 1 or more input sequences, subject to optional modifiers.
For comprehensions consist of a vector of bindings, with optional modifiers, and a user specified body in an implicit
do
block.Symbol bindings look like standard
let
bindings. Values bound to symbols should be sequences or otherwise seqable. The body of thefor
comprehension will be executed with the given symbol bound to successive values of the sequence. If multiple sequences are bound to symbols, iteration will proceed in a nested fashion with latest sequences iterated first and earlier sequences iterated later (as nestedfor
loops in procedural languages).For example, a simple non-nested for comprehension will yield:
(for [x [1 2 3 4]] x) ;;=> [1 2 3 4]
However, a nested comprehension will yield a longer sequence:
(for [x (range 3) y [:a :b :c]] [x y]) ;;=> ([0 :a] [0 :b] [0 :c] [1 :a] [1 :b] [1 :c] [2 :a] [2 :b] [2 :c])
Each set of symbol bindings may be modified by applying trailing bindings denoted with keywords. The keyword modifiers are:
- keyword
:let [sym val]
: :let
bindings work like any standard let bindings; destructuring is permitted; may refer to any previous bindings in other:let
modifiers or normal symbol bindings. Multiple pairs of bindings may appear in:let
bindings.- keyword
:when expr
: :when
bindings are applied to the sequence roughly like in the corefilter
function; the expression is evaluated and if it is not falsey, yield the next value. As with:let
bindings, the expression may refer to any previously bound names.- keyword
:while expr
: :while
bindings terminate the current sequence at the first point whenexpr
returns a falsey value.:while
bindings may refer to any previous bound names.
Multiple keyword modifiers may be applied to the previous binding. Their effects will be applied at the point they appear in the bindings vector.
- keyword
- fn (force x)[source]¶
If
x
is a Delay, returned the possibly cached value ofx
. Otherwise, returnx
.
- fn (frequencies coll)[source]¶
Return a map whose keys are the elements of
coll
and whose values are the counts for the number of times the key appears incoll
.
- macro (future & body)[source]¶
Execute the expressions of
body
in another thread. Returns a Future object. The value returned by the body can be fetched usingderef
or@
, though doing so may block unless thederef
with a timeout argument is used.
- fn (future-call f)[source]¶
- fn (future-call f pool)
Call the no args function
f
in another thread. Returns a Future object. The value returned byf
can be fetched usingderef
or@
, though doing so may block unless thederef
with a timeout argument is used.
- fn (future-cancel fut)[source]¶
Attempt to cancel the Future
fut
. If the future can be cancelled, returntrue
. Otherwise, returnfalse
.
- fn (future-cancelled? fut)[source]¶
Return
true
if the Futurefut
has been cancelled,false
otherwise.
- fn (gen-interface & opts)[source]¶
Generate and return a new Python interface (abstract base clase).
Options may be specified as key-value pairs. The following options are supported:
- keyword
:name
: the name of the interface as a string; required
- keyword
:extends
: a vector of interfaces the new interface should extend; optional
- keyword
:methods
: an optional vector of method signatures without
self
orthis
, like:[ (method-name [args ...] docstring) ... ]
Callers should use
definterface
to generate new interfaces.- keyword
- fn (gensym)[source]¶
- fn (gensym prefix)
Generate a unique symbol name of the form
prefix_#
. If noprefix
is given, thenv_
will be used.
- fn (get m k)[source]¶
- fn (get m k default)
Return the entry of
m
corresponding tok
if it exists ornil
ordefault
(if specified) otherwise.m
may be any associative type (such as a vector or map), set type, or string. Ifm
is not one of the supported types,get
always returnsnil
ordefault
(if specified).
- fn (get-in m ks)[source]¶
- fn (get-in m ks default)
Return the entry of an associative data structure addressed by the sequence of keys
ks
ordefault
(default:nil
) if the value is not found.
- fn (get-method multifn dispatch-val)[source]¶
Return the method of multimethod
multifn
which would respond todispatch-val
ornil
if no method exists fordispatch-val
.
- fn (get-thread-bindings)[source]¶
Return the current thread-local bindings as a map of Var/value pairs.
- fn (get-validator ref)[source]¶
Return the validator defined for the ref (Atom or Var), or
nil
if no validator is defined.
- fn (group-by f coll)[source]¶
Return a map whose keys are the result of calling
f
on each element incoll
and whose values are vectors of the values which produced the corresponding key, in the order they were added.
- fn (halt-when pred)[source]¶
- fn (halt-when pred retf)
Return a transducer which ends the tranducing process the first time
pred
returns a truthy value for an input.If
retf
is given, it will be passed two arguments if a halt occurs. The first argument is the current result and the second is the input which triggered the halt. The return value of callingretf
will be the return value of the transducer.If
retf
is not given, the defaultretf
will return the value which triggered the halt.
- macro (if-let binding true-cond false-cond)[source]¶
Evaluate the binding as with
let
, binding the given name for use in thetrue
expression iff the binding expression is truthy . Otherwise, return thefalse
expression without binding the name.
- macro (if-not cond true-cond false-cond)[source]¶
Evaluate
cond
and if it istrue
, returnfalse-cond
. Otherwise returntrue-cond
.
- macro (if-some binding true-cond false-cond)[source]¶
Evaluate the binding as with
let
, binding the given name for use in thetrue
expression iff the binding expression is notnil
. Otherwise, return thefalse
expression without binding the name.
- fn (ifn? x)[source]¶
Return
true
ifx
is callable as a function.Many Basilisp data structures are callable as functions though they are not proper function types.
- macro (import & modules)[source]¶
Import Python modules by name.
Modules may be specified either as symbols naming the full module path or as a vector taking the form
[full.module.path :as alias]
.Note that unlike in Python,
import
ed Python module names are always hoisted to the current Namespace, so imported names will be available within a Namespace even if theimport
itself occurs within a function or method.Use of
import
directly is discouraged in favor of the:import
directive in thens
macro.
- fn (in-ns & args)¶
- fn (int? & args)[source]¶
Return
true
ifx
is an :external:py:class`int`.Note that unlike Clojure, Basilisp uses Python integers and there is no distinction between standard and fixed-precision integers.
- fn (interleave)[source]¶
- fn (interleave coll)
- fn (interleave coll & colls)
Return a lazy sequence consisting of the first element of
coll` , then the first element of the following ``coll
, etc. until the shortest input collection is exhausted.
- fn (intern ns name)[source]¶
- fn (intern ns name val)
Finds or creates a Var in
ns
(which may be either a namespace or symbol), setting the root binding toval
, if provided. The namespace must exist. Return the Var.
- fn (interpose sep)[source]¶
- fn (interpose sep coll)
Return a lazy sequence of elements of
coll
separated bysep
. Ifcoll
is empty, return an empty sequence.Return a stateful transducer if no collection is provided.
- fn (into)[source]¶
- fn (into to)
- fn (into to from)
- fn (into to xform from)
Return a new collection created by adding all of the elements of
from
to the existing to collectionto
, as byconj
.A transducer may be provided as
xform
to transform the elements as they are copied.into
will attempt to use transient collections whenever possible to improve performance.
- fn (into-array aseq)[source]¶
- fn (into-array type aseq)
Returns a Python list with the values from
aseq
.The type argument is ignored and is provided only for Clojure compatibility.
- fn (ints x)[source]¶
Dummy cast to a Python list of integers.
This function is provided for Clojure compatibility.
- fn (isa? tag parent)[source]¶
- fn (isa? h tag parent)
Return true if
tag
is equal toparent
or is a descendant ofparent
in hierarchyh
.Both
tag
andparent
may be a valid Python type or a namespace-qualified keyword or symbol or a vector of namespace-qualified keywords or symbols. If either oftag
orparent
is a vector, the other must be a vector as well.Ancestors will be fetched for
tag
usingancestors
.h
must be a hierarchy returned bymake-hierarchy
. Ifh
is not supplied, the global hierarchy will be used.
- fn (iteration step & {:or {kf identity initk nil somef some? vf identity} :keys [somef vf kf initk]})[source]¶
Return a reducible sequence via repeated calls to
step
, a function of a “continuation token”,k
.step
will initially be called withinitk
. Given a return value of that call,ret
, if(somef ret)
returns a truthy value, the result of(vf ret)
will be included in the sequence. Otherwise, the sequence will terminate and neitherkf
norvf
will be called. If the iteration continues,step
will be called again with the result of(kf ret)
.Only
step
is a required argument.somef
defaults tosome?
,vf
andkf
default toidentity
, andinitk
defaults tonil
.For the purposes of this function,
step
should be considered an impure function and repeated calls to it even with the same token may not necesarily return the same values.
- fn (juxt & args)[source]¶
Return a function which takes any number of arguments and applies each of the argument functions to this function in order, returning a vector of the return values from each function.
- fn (keep f)[source]¶
- fn (keep f coll)
Return a lazy sequence of non-
nil
results of(f elem)
for elements incoll
.Return a transducer if no collection is provided.
- fn (keep-indexed f)[source]¶
- fn (keep-indexed f coll)
Return a lazy-sequence of non-
nil
results of(f index elem)
for elements incoll
.Return a stateful transducer if no collection is provided.
- fn (keyword name)[source]¶
- fn (keyword ns name)
Create a new keyword with
name
and optional namespacens
. Keywords will have the colon prefix added automatically, so it should not be provided.name
may be keyword, symbol, or string. Ifname
is a keyword or symbol with a namespace, the namespace will be included in the resulting value.If
ns
is notnil
, then bothname
andns
must be strings.
- macro (lazy-cat & colls)[source]¶
Return a lazy sequence of the concatenation of
colls
. None of the input collections will be evaluated until it is needed.
- macro (lazy-seq & body)[source]¶
Takes a body of expressions which will produce a seq or
nil
. Whenseq
is first called on the resultinglazy-seq
, the sequence will be realized.
- macro (let bindings & body)[source]¶
let
bindings with Destructuring support.
- macro (letfn bindings & body)[source]¶
Let form specifically for local function definitions.
Functions are defined as bindings:
(letfn [(plus-two [x] (+ (plus-one x) 1)) (plus-one [x] (+ x 1))] (plus-two 3))
Functions defined in
letfn
bindings may refer to each other regardless of their order of definition.See
letfn
for more details.
- fn (lisp->py o)[source]¶
- fn (lisp->py o & {:or {keyword-fn name} :keys [keyword-fn]})
Recursively convert Basilisp data structures into Python data structures.
Callers can specify a keyword argument
:keyword-fn
, which names a function which is called for each keyword value in the input structure to return a new value. By default:keyword-fn
is the functionname
.
- fn (load & paths)[source]¶
Read and evaluate the set of forms contained in the files identified by
paths
.The provided paths should not include a file suffix.
Most often this is useful if you want to split your namespace across multiple source files.
require
will try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario).load
will load the contents of the named file directly into the current namespace.A path is interpreted relative to the syspath if it starts with a forward slash or relative to the root directory of the current namespace otherwise.
Note that unlike
require
, files loaded byload
will not be cached and will thus incur compilation time on subsequent loads.This function is provided for compatibility with Clojure. Users should prefer
load-file
(or perhapsload-reader
orload-string
) to this function.
- fn (load-file path)[source]¶
Read and evaluate the set of forms contained in the file located at
path
.Most often this is useful if you want to split your namespace across multiple source files.
require
will try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario).load-file
will load the contents of the named file directly into the current namespace.Note that unlike
require
, files loaded byload-file
will not be cached and will thus incur compilation time on subsequent loads.
- fn (load-reader reader)[source]¶
Read and evaluate the set of forms in the
io.TextIOBase
instancereader
.Most often this is useful if you want to split your namespace across multiple source files.
require
will try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario).load-reader
will load the contents of the named file directly into the current namespace.Note that unlike
require
, files loaded byload-reader
will not be cached and will thus incur compilation time on subsequent loads.
- fn (loaded-libs)[source]¶
Return a set of all loaded Basilisp namespace names as symbols.
Namespace names are only added to this list if they appear in an
ns
macro.
- fn (long x)[source]¶
Coerce
x
to anint
.Python does not support long types, so the value is coerced to an integer as by
int
.
- fn (longs x)[source]¶
Dummy cast to a Python list of longs.
This function is provided for Clojure compatibility.
- macro (loop bindings & body)[source]¶
loop
bindings with Destructuring support.
- fn (macroexpand form)[source]¶
Repeatedly macroexpand
form
as bymacroexpand-1
until form no longer represents a macro. Returns the expanded form. Does not macroexpand child forms.
- fn (macroexpand-1 form)[source]¶
Macroexpand
form
one time. Returns the macroexpanded form. The return value may still represent a macro. Does not macroexpand child forms.
- fn (make-array size)[source]¶
- fn (make-array type size)
- fn (make-array type size & more-sizes)
Create a Python list with initial
size
. If multiple sizes are provided, produces a multi-dimensional list-of-lists. There is no efficient way to allocate such multi-dimensional lists in Python, so this function will run in polynomial time.Python lists do not support pre-allocation by capacity, so this function pre-fills the created list(s) with
nil
.The
type
argument is ignored and is provided only for Clojure compatibility.
- fn (make-hierarchy)[source]¶
Return a hierarchy that may be used to establish parent and child relationships via
derive
(relationships may be removed viaunderive
).Relationships can be queried using
ancestors
,descendants
,parents
, andisa?
.
- fn (map f)[source]¶
- fn (map f coll)
- fn (map f coll & colls)
Return a lazy sequence of
(f elem)
for elements incoll
. More than one collection may be supplied. If more than one collection is supplied, the functionf
will be passed sequential elements from each collection on each invocation and must be able to accept as many arguments as there are collections. The sequence will terminate when at least one input collection is exhausted.Return a transducer if no collection is provided.
- fn (map-entry coll)[source]¶
- fn (map-entry k v)
With one argument, coerce the input to a map entry. With two arguments, return a map entry containing
key
andvalue
.
- fn (map-entry? x)[source]¶
Return
true
ifx
implementsbasilisp.lang.interfaces.IMapEntry
.
- fn (map-indexed f)[source]¶
- fn (map-indexed f coll)
Return a lazy sequence of
(f idx elem)
for elements incoll
. The index starts at 0.Return a stateful transducer if no collection is provided.
- fn (mapcat f)[source]¶
- fn (mapcat f coll)
- fn (mapcat f coll & colls)
Return a lazy sequence of the concatenated results of mapping
f
overcolls
.
- fn (mapv & args)[source]¶
Return a vector of
(f elem)
for elements incoll
. More than one collection may be supplied. If more than one collection is supplied, the functionf
will be passed sequential elements from each collection on each invocation and must be able to accept as many arguments as there are collections. The sequence will terminate when at least one input collection is exhausted.
- fn (max-key k & args)[source]¶
Return the arg for which
(k arg)
is the largest number. If multiple values return the same number, return the last.
- macro (memfn name & args)[source]¶
Expands into a function that calls the method
name
on the first argument of the resulting function. Ifargs
are provided, the resulting function will have arguments of these names.This is a convenient way of producing a first-class function for a Python method.
- fn (memoize f)[source]¶
Retuns a fn that caches the results of the previous invocations of
f
.The memoized fn keeps a cache of the mapping from arguments to results.
- fn (merge & maps)[source]¶
Merge maps together from left to right as by
conj
. If a duplicate key appears in a map, the rightmost map’s value for that key will be taken.
- fn (merge-with f & maps)[source]¶
Merge maps together from left to right as by
conj
. If a duplicate key appears in a map, the resulting value of that key in the merged result will be the result of calling(f current-val next-val)
.
- fn (min-key k & args)[source]¶
Return the arg for which
(k arg)
is the smallest number. If multiple values return the same number, return the last.
- fn (mod num div)[source]¶
Returns the modulo of
num
anddiv
.It uses floored division for calculating the quotient.
- multi fn (munge & args)[source]¶
Munge the input value into a Python-safe string. Converts keywords and symbols into strings as by
name
prior to munging.Returns a string.
- multi fn (namespace-munge & args)[source]¶
Convert a Basilisp namespace name to a valid Python name.
- macro (new class & args)[source]¶
Create a new instance of
class
withargs
.New objects may be created as any of:
(new python/str *args) (new python.str *args) (new python.str. *args)
This is compatibility syntax for Clojure, since Python (and therefore Basilisp) do not require the
new
keyword for object instantiation.
- fn (next seq)[source]¶
Calls
rest
ono
. Ifo
returns an empty sequence ornil
, returnsnil
. Otherwise, returns the elements after the first ino
.
- macro (ns name & opts)[source]¶
Use this namespace pre-amble at the top of every namespace to declare the namespace name and import necessary Python modules and require Basilisp namespaces.
You may include an optional docstring for the namespace to describe its purpose. The docstring will be applied as the
:doc
key on the namespace metadata map.Example:
(ns my.namespace "My namespace with code" (:refer-basilisp :exclude [get]) (:require [basilisp.string :as str]) (:use [basilisp.set :only [intersection]]) (:import inspect))
Flags and contents of each of the various sections are detailed further at each of their respective function definitions.
:refer-basilisp
(:refer-clojure
is also accepted) controls how names frombasilisp.core
are exposed in the namespace. Refer torefer
for usage.:require
imports other Basilisp namespaces. Refer torequire
for usage.:use
is a variant of:require
, although:require
is preferred in most cases. Seeuse
for usage.:import
imports Python modules and packages. Refer toimport
for usage.
Use of the
ns
macro to control requires and imports is recommended in all cases. The various functions thatns
delegates to and whose documentation are referred to above are generally useful for interactive usage at the REPL but not appropriate for usage in a larger application.
- fn (ns-aliases ns)[source]¶
Return a map of Basilisp namespaces which are aliased in the current namespace.
- fn (ns-imports ns)[source]¶
Return a set of Python modules which are imported in the current namespace.
- fn (ns-interns ns)[source]¶
Return a map of symbols to Vars which are interned in the current namespace.
- fn (ns-map)[source]¶
- fn (ns-map ns)
Return a map of all the mapped symbols in the namespace.
Includes the return values of
ns-interns
andns-refers
in one map.
- fn (ns-publics ns)[source]¶
Return a map of symbols to public Vars which are interned in the current namespace.
Public vars are Vars which are declared without
:private
metadata.
- fn (ns-refers ns)[source]¶
Return a map of symbols to Vars which are referred in the current namespace.
- fn (ns-resolve ns sym)[source]¶
Return the Var which will be resolved by the symbol in the given namespace.
- fn (nth coll i)[source]¶
- fn (nth coll i notfound)
Returns the
i
th element ofcoll
(0-indexed), if it exists ornil
otherwise. Ifi
is out of bounds, throws anIndexError
unlessnotfound
is specified.coll
may be any sequential collection type (such as a list or vector), string, ornil
. Ifcoll
is not one of the supported types, aTypeError
will be thrown.
- fn (nthnext coll i)[source]¶
Returns the nth next sequence of
coll
.(nthnext nil 1) ;=> nil (nthnext [] 1) ;=> nil (nthnext [1 2 3 4 5 6] 4) ;=> (5 6)
- fn (nthrest coll i)[source]¶
Returns the nth rest sequence of
coll
, orcoll
ifi
is 0.(nthrest nil 1) ;=> nil (nthrest [] 1) ;=> [] (nthrest [1 2 3 4 5 6] 4) ;=> (5 6)
- fn (object-array size-or-seq)[source]¶
- fn (object-array size init-val-or-seq)
Create an array of objects.
If
init-val-or-seq
and is aseq
yielding fewer thansize
elements, then the remaining indices of the resulting array will be filled withnil
values.This function does not coerce its argument and is provided for Clojure compatibility.
- macro (or)[source]¶
- macro (or & args)
Evaluate the expressions from left to right. Returns the first truthy expression. Otherwise, returns the final falsey expression. Calling
or
with no arguments returnsnil
.
- fn (parents tag)[source]¶
- fn (parents h tag)
Return the set of all direct parents of
tag
in hierarchyh
.tag
may be either a valid Python type or a namespace-qualified keyword or symbol. Iftag
is a Python type, ancestors include any relationships established via calls toderive
as well as any immediate superclasses (as returned bybases
). Iftag
is a namespace-qualified keyword, only relationships fromderive
are returned.h
must be a hierarchy returned bymake-hierarchy
. Ifh
is not supplied, the global hierarchy will be used.
- fn (parse-boolean s)[source]¶
Parse the string argument
s
as either booleantrue
orfalse
returning the boolean if the string contains one, ornil
otherwise.This function will throw a
TypeError
for non-string types.
- fn (parse-double s)[source]¶
Parse the string argument
s
as a floating point number as by Python’s builtinfloat
function, returning the float if the string contains one, ornil
otherwise.This function will throw a
TypeError
for non-string types.
- fn (parse-long s)[source]¶
Parse the string argument
s
as an integer (base 10) as by Python’s builtinint
function, returning the integer if the string contains one, ornil
otherwise.This function will throw a
TypeError
for non-string types.
- fn (parse-uuid s)[source]¶
Parse the string argument
s
as auuid.UUID
, returning the UUID if the string contains one, ornil
otherwise.This function will throw a
TypeError
for non-string types.
- fn (partial f)[source]¶
- fn (partial f & args)
Return a function which is the partial application of
f
withargs
.
- fn (partial-kw f)[source]¶
- fn (partial-kw f m)
- fn (partial-kw f arg & args)
Return a function which is the partial application of
f
with keyword arguments.If a single argument is provided, it will be interpreted as a map of keyword arguments.
If multiple arguments are given, they are interpreted as key/value pairs and will be converted into a hash-map before being partially applied to the function.
This function applies keyword arguments via apply-kw. As a consequence, Lisp keywords will be converted to munged Python strings (via
name
), meaning namespaces will be lost and identifiers which are not valid Python syntax will be converted to safe Python identifiers.
- fn (partition n coll)[source]¶
- fn (partition n step coll)
- fn (partition n step pad coll)
Return a lazy sequence of partitions of
coll
of sizen
at offsets ofstep
elements. Ifstep
is not given, steps of sizen
will be used and there will be no overlap between partitions. Ifpad
is given, partition will pull elements frompad
until the final sequence is equal to sizen
. If there are fewer thann
leftover elements incoll
, they will not be returned as a partial partition.
- fn (partition-all n)[source]¶
- fn (partition-all n coll)
- fn (partition-all n step coll)
Return a lazy sequence of partitions of
coll
of sizen
at offsets ofstep
elements. Ifstep
is not given, steps of sizen
will be used and there will be no overlap between partitions. If there are leftover elements fromcoll
which do not fill a full partition, then a partial partition will be returned, unlikepartition
.Return a stateful transducer if no collection is provided.
- fn (partition-by f)[source]¶
- fn (partition-by f coll)
Return a lazy sequence of partitions, splitting
coll
each timef
returns a different value.Returns a stateful transducer if no collection is provided.
- fn (pcalls & fns)[source]¶
Return a lazy seq of the result of executing the no arg functions
fns
, which will be evaluated in parallel.
- fn (peek coll)[source]¶
For a list or a queue, return the first element.
For a vector, return the last element (more efficiently than by last).
For empty collections, returns
nil
.
- fn (persistent! coll)[source]¶
Return a persistent copy of the transient collection
coll
which was created by callingtransient
.
- fn (pmap f coll)[source]¶
- fn (pmap f coll & colls)
Apply
f
as bymap
, but in parallel using futures.This may only be useful for functions which are mainly blocked on IO, since Python threads do not allow parallel computation using threads.
This function is not fully lazy. Chunks of elements from the input collection are grabbed eagerly to spawn Futures of
f
. Elements after the chunk size in the input collection are grabbed lazily. The chunk size is set by*pmap-cpu-count*
and defaults to 2 times the number of CPU cores on the machine; the value of*pmap-cpu-count*
is captured whenpmap
is first called, so it should be safe to bind in the initial calling thread. The sequence of futures is fed into a final (fully lazy) sequence to deref the Future and return its final value.
- fn (pop coll)[source]¶
For a list or a queue, return a new list without the first element.
For a vector, return a new vector without the last element.
If
coll
is empty, throw an exception.
- fn (pop! coll)[source]¶
Return a new transient vector without the last element of
coll
. Ifcoll
is empty, throw an exception.
- fn (pop-thread-bindings)[source]¶
Pop thread bindings set by a corresponding call to
push-thread-bindings
. This should not be called without a prior call topush-thread-bindings
.
- dynamic Var pr[source]¶
Print the arguments to the stream bound to
*out*
in a format which is readable by the Basilisp reader. Multiple arguments will be separated by the string value bound to*print-sep*
(default is an ASCII space).Note that some dynamically created Basilisp forms (such keywords and symbols) and Python objects may not be readable again.
It can be dynamically bound.
- fn (prefer-method multifn dispatch-val-x dispatch-val-y)[source]¶
Update the mulitmethod
multifn
to preferdispatch-val-x
overdispatch-val-y
in cases where the dispatch value selection might be ambiguous between the two.Returns the multimethod.
- fn (prefers multifn)[source]¶
Return a map of the set of preferred values to the set of other conflicting values.
- fn (print)[source]¶
- fn (print x)
- fn (print x & args)
Print the arguments to the stream bound to
*out*
in a format which is readable by humans. Multiple arguments will be separated by the string value bound to*print-sep*
(default is an ASCII space).
- fn (println)[source]¶
- fn (println x)
- fn (println x & args)
Print the arguments to the stream bound to
*out*
in a format which is readable by humans.println
always prints a trailing newline. Multiple arguments will be separated by the string value bound to*print-sep*
(default is an ASCII space).Observes
*flush-on-newline*
.
- fn (prn)[source]¶
- fn (prn x)
- fn (prn x & args)
Same as
pr
, but appending a newline afterwards.Observes
*flush-on-newline*
.
- fn (promise)[source]¶
Return a promise object which can be set exactly once using
deliver
. Readers may block waiting for the value of the promise using@
orderef
. If the value has already been realized, then reading the value of the promise will not block. Readers may check if the promise has been delivered usingrealized?
.
- fn (push-thread-bindings bindings)[source]¶
Takes a map of Var/value pairs and applies the given value to the Var in the current thread.
This call should be accompanied with a
pop-thread-bindings
call in atry
/finally
block.This function is a very low level function and its use is discouraged in favor of a higher level construct like the
binding
macro.
- macro (pvalues & exprs)[source]¶
Returns a lazy seq of the result of
exprs
, which will be evaluated in parallel.
- fn (py->lisp o)[source]¶
- fn (py->lisp o & {:or {keywordize-keys true} :keys [keywordize-keys]})
Recursively convert Python data structures into Basilisp data structures.
Callers can specify a keyword argument
:keywordize-keys
, which defaults totrue
. If`:keywordize-keys is ``true
, then all string keys in Pythondicts
will be converted into keywords in the final return value.
- fn (rand)[source]¶
- fn (rand upper)
- fn (rand lower upper)
Return a random real number between
lower
(default: 0) andupper
(default: 1) inclusive.
- fn (rand-int upper)[source]¶
- fn (rand-int lower upper)
Return a random integer between
lower
(default: 0) andupper
inclusive.
- fn (random-sample prob)[source]¶
- fn (random-sample prob coll)
Return elements from
coll
with the random probability ofprob
.Return a transducer if no collection is provided.
- fn (range)[source]¶
- fn (range end)
- fn (range start end)
- fn (range start end step)
Return a range of integers from
start
. Ifend
is specified, the sequence will terminate atend
.
- fn (ratio? x)[source]¶
Return
true
ifx
is afractions.Fraction
.
- fn (re-find pattern s)[source]¶
Returns the first match of a string to a pattern using
re.search()
.If the string matches the pattern exactly and there are no match groups, return the string. Otherwise, return a vector with the string in the first position and the match groups in the following positions.
- fn (re-matches pattern s)[source]¶
Returns a match of a string to a pattern using
re.fullmatch()
.If the string matches the pattern exactly and there are no match groups, return the string. Otherwise, return a vector with the string in the first position and the match groups in the following positions.
- fn (re-pattern s)[source]¶
Return a new
re.Pattern
instance.
- fn (re-seq pattern s)[source]¶
Returns a lazy sequence of matches of a string to a pattern using
re.finditer()
.If the string matches the pattern exactly and there are no match groups, return the string. Otherwise, return a vector with the string in the first position and the match groups in the following positions.
- fn (read)[source]¶
- fn (read stream)
- fn (read opts stream)
- fn (read stream eof-error? eof-value)
Read the next form from the
stream
. If no stream is specified, uses the value currently bound to*in*
.Callers may bind a map of readers to
*data-readers*
to customize the data readers used reading this string.The stream must satisfy the interface of
io.TextIOBase
, but does not require any pushback capabilities. The defaultbasilisp.lang.reader.StreamReader
can wrap any object implementingTextIOBase
and provide pushback capabilities.
- fn (read-string s)[source]¶
- fn (read-string opts s)
Read a string of Basilisp code.
Callers may bind a map of readers to
*data-readers*
to customize the data readers used reading this string.Note that
read-string
should not be used to read string input from untrusted sources. For reading EDN input from untrusted sources, instead consider usingbasilisp.edn
.
- fn (realized? o)[source]¶
Return
true
if the delay, future, lazy sequence, or promise has been realized.
- fn (reduce f coll)[source]¶
- fn (reduce f val coll)
Reduce
coll
byf
.If
val
is not supplied andcoll
has no elements,f
will be called with no arguments and the result will be returned.If
val
is not supplied andcoll
has one element, the result of(f (first val))
is returned.If
val
is not supplied andcoll
has elements, repeatedly reducecoll
by callingf
on successive elements incoll
.If
val
is supplied andcoll
has no elements, returnval` and ``f
will not be called.If
val
is supplied andcoll
has elements, repeatedly reducecoll
by callingf
on successive elements incoll
, starting withval
.If
f
returns areduced
value at any point, reduction will terminate and the reduced value will be returned immediately.
- fn (reduce-kv f init coll)[source]¶
Reduce an associative
coll
byf
.f
must be a function of 3 arguments: the initially supplied valueinit
(in later invocations, the return from previous invocations), the key of an entry ofcoll
, and the value of an entry ofcoll
.If
coll
has no elements,init
is returned andf
is not called.If
f
returns areduced
value at any point, reduction will terminate and the reduced value will be returned immediately.reduce-kv
may reduce vectors in addition to maps. Vectors have non-negative integer keys.
- fn (reduced x)[source]¶
Wraps a value
x
such that it will terminate a reduce operation.Callers can retrieve the inner reduced value using
deref
or@x
.
- fn (refer ns-sym & filters)[source]¶
Refer Vars from the namespace named by
ns-sym
, subject to the filters specified.Supported filters:
:only [sym1 sym2]
to only refer the specified symbols:exclude [sym1, sym2]
to refer all except the specified symbols:rename {sym1 new-sym1}
to rename all the specified symbols to the given new name
Use of
refer
directly is discouraged in favor of the:refer
modifier in the:require
directive of thens
macro or the:use
directive of thens
macro.
- fn (refer-basilisp & args)[source]¶
Refer Vars from
basilisp.core
using the same filter syntax asrefer
.
- fn (refer-clojure & args)[source]¶
Compatibility layer with JVM Clojure, which points to
refer-basilisp
.
- macro (reify & method-impls)[source]¶
Create a new Python object of an anonymous type which implements 0 or more Python interfaces or Basilisp protocols.
Unlike types created via
deftype
,reify
returns an object which implements the named interfaces using the implementations provided. You may not provide fields as such toreify
, thoughreify
closes over any local names defined in the same lexical context. These fields may serve as private fields of the created object.Interface or protocol implementations are declared as the name of the interface or protocol as a symbol, followed by 1 or more method definitions for that interface. Types are not required to declare any interface implementations. Types which do declare interface implementations are required to implement all interface methods. Failing to implement all interface methods is a compile time error. Types implementing
object
are not required to implement allobject
methods.Method declarations should appear as:
(method-name [arg1] & body) (method-name [arg1 arg2 ...] & body)
Unlike in Clojure, interface and protocol methods are permitted to include variadic arguments. Single-arity methods may also declare support for keyword arguments using either the
:apply
or:collect
strategy on the:kwargs
metadata on the method name. Finally, single-arity methods may be declared as Python properties using the:property
metadata on the method name. These facilities are provided as a means to interoperate with Python code and their use is discouraged in pure Basilisp code.reify
does not support class method or static method members and attempting to declarereify
members as class or static members will result in a compile time error.Type objects are created with sensible
object
defaults as byattrs
. New types may overrideobject
defaults.Reified objects always implement
basilisp.lang.interfaces/IWithMeta
and transfer the metadata from the form to the created object.Methods must supply a
this
orself
parameter.recur
special forms used in the body of a method should not include that parameter, as it will be supplied automatically.
- fn (rem num div)[source]¶
Returns the remainder of
num
anddiv
.It uses truncated division for calculating the quotient.
- fn (remove pred)[source]¶
- fn (remove pred coll)
Return elements from
coll
where(pred elem)
returns a falsey value.Return a transducer if no collection is provided.
- fn (remove-all-methods multifn)[source]¶
Remove all methods for the multimethod
multifn
.Return the multimethod.
- fn (remove-method multifn dispatch-val)[source]¶
Remove the method from the multimethod
multifn
which responds todispatch-val
, if it exists.Return the multimethod.
- fn (remove-tap tf)[source]¶
- fn (remove-tap topic tf)
Remove a tap function from the tap set added by
add-tap
.Tap functions may only be removed from the tap set corresponding to the topic they were added with. If no topic is given, the default topic is used.
Returns
nil
in all cases.
- fn (remove-watch ref k)[source]¶
Remove the watch function identified by
k
from the ref (Atom or Var), if it exists. Returns the ref.
- fn (repeat x)[source]¶
- fn (repeat n x)
Repeat
x
infinitely orn
many times ifn
is specified. Returns a lazy sequence of thex
.
- fn (repeatedly f)[source]¶
- fn (repeatedly n f)
Call
f
infinitely orn
many times ifn
is specified. Returns a lazy sequence of the return values.
- fn (replace smap)[source]¶
- fn (replace smap coll)
Replace elements of the vector/seq
coll
with matching elements from the associative collectionsmap
, if they exist.Return a transducer if no collection is provided.
- fn (require & args)[source]¶
Load Basilisp libraries and make them accessible in the current namespace.
Arguments should be libspecs, which take the following forms:
symbols, which name fully qualified namespaces
vectors, which take the form
[namespace-symbol & opts]
Vector libspec arguments must be one of:
:as name
which will alias the imported namespace to the symbol name:as-alias name
which will alias the namespace to the symbol name but not require the namespace, which can be useful for namespaces used primarily for keywords; the namespace need not exist at all; can be combined with:as
:refer [& syms]
which will refer syms in the local namespace directly:refer :all
which will refer all symbols from the namespace directly
Use of
require
directly is discouraged in favor of the:require
directive in thens
macro.
- fn (requiring-resolve sym)[source]¶
Resolve the namespaced symbol
sym
as byresolve
. If resolution fails, attempts to requiresym
‘s namespace (as byrequire
) before resolving again.
- fn (reset! atom v)[source]¶
Reset the value of an atom to
v
without regard to the previous value. Return the new value.
- fn (reset-meta! o meta)[source]¶
Atomically swap the metadata on reference
o
to meta. References include atoms, namespaces, and vars.
- fn (reset-vals! atom v)[source]¶
Reset the value of an atom to
v
without regard to the previous value. Return a vector containing the new value and the old value in that order.
- fn (resolve sym)[source]¶
Return the Var which will be resolved by the symbol in the namespace currently bound to
*ns*
.
- fn (rest seq)[source]¶
If
seq
is a Seq, return the elements after the first inseq
. Ifseq
isnil
, returns an empty seq. Otherwise, coercesseq
to a seq and returns the rest.
- fn (reverse coll)[source]¶
Return a seq containing the elements in
coll
in reverse order. The returned sequence is not lazy.
- fn (reversible? x)[source]¶
Return
true
if x implementsbasilisp.lang.interfaces.IReversible
.
- fn (rseq coll)[source]¶
Return a sequence of the elements of
coll
in reverse order in constant time. Only Vectors support this operation.
- fn (satisfies? {:as proto :keys [interface impls]} x)[source]¶
Return true if
x
satisfies protocolproto
.
- fn (seqable? x)[source]¶
Return
true
if anbasilisp.lang.interfaces.ISeq
can be produced fromx
.
- fn (sequence coll)[source]¶
- fn (sequence xform coll)
- fn (sequence xform coll & colls)
Coerces
coll
to a possibly empty sequence. Ifcoll
isnil
, return()
.When a transducer
xform
is supplied, returns a lazy sequence of the transform to elements ofcoll
. If multiple collections are provided,xform
must support as many arguments as there are collections.If multiple collections are provided, the resulting sequence will terminate when any one of the inputs is exhausted.
- fn (sequential? x)[source]¶
Return
true
ifx
implementsbasilisp.lang.interfaces.ISequential
.
- fn (set-validator! ref vf)[source]¶
Set the validator function for the ref (Atom or Var).
Validator functions should be side-effect free functions of one argument: the proposed new value of the ref. The validator should either return false or throw an error if the ref value is invalid.
nil
may be passed to remove the validator for a ref.If the existing ref value is not valid according to
vf
, an exception will be thrown and the new validator function will not be applied.
- fn (short x)[source]¶
Coerce
x
to anint
.Python does not support short types, so the value is coerced to an integer as by
int
.
- fn (shorts x)[source]¶
Dummy cast to a Python list of shorts.
This function is provided for Clojure compatibility.
- fn (slurp f & opts)[source]¶
Open a
basilisp.io/reader
instance onf
and read the contents off
into a string.Options may be provided as key value pairs and will be passed directly to
basilisp.io/reader
. Supported reader options depend on which type of reader is selected forf
. Most readers support the:encoding
option.If
f
is a string, it first is resolved as a URL (viaurllib.parse.urlparse
). If the URL is invalid or refers to a filesystem location (viafile://
scheme), then it will be resolved as a local filesystem path.Return the string contents.
- macro (some-> x & forms)[source]¶
Thread
x
through the forms (as by->
) until the resulting expression isnil
or there are no more forms.
- macro (some->> x & forms)[source]¶
Thread
x
through the forms (as by->>
) until the resulting expression isnil
or there are no more forms.
- fn (some-fn f)[source]¶
- fn (some-fn f & fs)
Return a predicate composed of all of the input functions, which returns the first truthy return value from one of the inputs, otherwise returns
nil
. The returned predicate returns the first truthy value it encounters and will not execute any remaining functions.
- fn (sort coll)[source]¶
- fn (sort cmp coll)
Return a sorted sequence of the elements from
coll
using thecmp
comparator.The
compare
fn is used in ifcmp
is not provided.
- fn (sort-by keyfn coll)[source]¶
- fn (sort-by keyfn cmp coll)
Return a sorted sequence of the elements from
coll
using thecmp
comparator on (keyfn
item).The
compare
fn is used in ifcmp
is not provided.
- fn (spit f content & opts)[source]¶
Open a
basilisp.io/writer
instance onf
and writecontent
out tof
before closing the writer.Options may be provided as key value pairs and will be passed directly to
basilisp.io/writer
. Supported writer options depend on which type of writer is selected forf
. Most writers support the:encoding
option.If
f
is a string, it first is resolved as a URL (viaurllib.parse.urlparse
). If the URL is invalid or refers to a filesystem location (viafile://
scheme), then it will be resolved as a local filesystem path.spit
does not support writing to non-file URLs.Return
nil
.
- fn (split-at n coll)[source]¶
Split a collection at the
n
th item. Returns a vector of[(take n coll) (drop n coll)]
.
- fn (split-with pred coll)[source]¶
Split a collection at the inflection point of
pred
. Returns a vector of[(take-while pred coll) (drop-while pred coll)]
.
- fn (str)[source]¶
- fn (str o)
- fn (str o & args)
Create a string representation of
o
.Return the empty string if
o
is nil.
- fn (subclasses cls)[source]¶
Return a set of subclasses of
cls
.This set is not guaranteed to be exhaustive because classes only retain a weak reference to their subclasses, so it is possible subclasses of
cls
have been garbage collected.
- fn (subs s start)[source]¶
- fn (subs s start end)
Return a substring of
s
from the indexstart
(inclusive) to indexend
exclusive, or the end of the string if noend
is supplied.
- fn (subvec v start)[source]¶
- fn (subvec v start end)
Return a vector of elements consisting of the elements of
v
from the indexstart
(inclusive) to indexend
exclusive, or the end of the vector if noend
is supplied.
- fn (supers cls)[source]¶
Return the direct and indirect superclasses and interfaces of
cls
as a set.
- fn (swap! atom f & args)[source]¶
Atomically swap the value of an atom to the return value of
(apply f current-value args)
. The functionf
may be called multiple times while swapping, so should be free of side effects. Return the new value.
- fn (swap-vals! atom f & args)[source]¶
Atomically swap the value of an atom to the return value of
(apply f current-value args)
. The functionf
may be called multiple times while swapping, so should be free of side effects. Return a vector containing the new value and the old value in that order.
- fn (symbol name)[source]¶
- fn (symbol ns name)
Create a new symbol with
name
and optional namespacens
.name
may be keyword, symbol, string, or Var. Ifname
is a keyword or symbol with a namespace, the namespace will be included in the resulting value. Ifname
is a Var, the Var’s namespace will always be the namespace of the resulting value.If
ns
is notnil
, then bothname
andns
must be strings.
- fn (take-nth n)[source]¶
- fn (take-nth n coll)
Return a lazy sequence of every
n
th element ofcoll
.Return a stateful transducer if no collection is provided.
- fn (take-while pred)[source]¶
- fn (take-while pred coll)
Return elements of
coll
while(pred elem)
istrue
.Return a transducer if no collection is provided.
- fn (tap> val)[source]¶
- fn (tap> topic val)
Send the value
val
to all tap functions registered for the topic. If no topic is given, the default topic is used.tap>
will never block, though if the tap queue is full then tap values may be dropped.Returns true if
val
was sent to the queue,false
ifval
was dropped.
- fn (the-ns v)[source]¶
If
v
is a symbol, return the Namespace named by that symbol if it exists. Ifv
is a Namespace, return it. Otherwise, throw an exception.
- fn (thread-bound? & vars)[source]¶
Return
true
if vars are thread-bound, which implies that aset!
will succeed. Returnstrue
if no vars are given.
- macro (time expr)[source]¶
Time the execution of
expr
. Return the result ofexpr
and print the time execution took in milliseconds.
- fn (to-array-2d coll)[source]¶
Return a two-dimensional Python list from the contents of
coll
.Python lists do not specify a fixed size, so the resulting two-dimensional list may be ragged (in the Java sense of the word) if the inner collections of the input are ragged.
- fn (trampoline f & args)[source]¶
Trampoline
f
with starting arguments. Iff
returns a function (as determined byfn?
), call its return value with no arguments, repeating that process until the return value is not a function.
- fn (transduce xform f coll)[source]¶
- fn (transduce xform f init coll)
Reduce
coll
by the transducing functionxf
(created as(xform f)
).If
coll
is empty, returninit
without callingf
. Ifinit
is not given,f
will be called with no arguments to produce it.The transducing process will eagerly consume the input collection, calling
xf
on the result of the previous call (or init on the first invocation) and the next value from the input collection, until either the collection is exhausted orxf
returns areduced
value. In both cases, thexf
‘s 1-arity will be called with result and that result will be returned.
- fn (transient coll)[source]¶
Return a transient copy of persistent collection
coll
.Transients can be created from maps, sets, and vectors. Transients allow faster mutations than their persistent counterparts and are useful for performance sensitive code which makes many modifications to these data structures.
Transient collections can be edited with the transient versions of the familiar collection functions (depending on the type of
coll
):assoc!
,conj!
,disj!
,dissoc!
, andpop!
. Transient collections are designed to be used in the same style as the builtin persistent collections, so callers should be sure to use the returned value from prior calls to these collection functions rather than repeatedly modifying the collection in place.Once you have completed all of your modifications to the local transient collection, you can call
persistent!
to return a persistent version of that data structure.
- fn (tree-seq branch? children root)[source]¶
Return a lazy seq on the nodes of the tree-like data structure
root
.branch?
should be a function of a single argument which should returntrue
if a node might contain children (though it need not).children
should be a function of one argument which should return a sequence of children of a node.children
will only be called on a node ifbranch?
returnstrue
for that node.
- fn (unchecked-add)[source]¶
- fn (unchecked-add x)
- fn (unchecked-add x y)
- fn (unchecked-add x y & args)
Sum the arguments together. If no arguments given, returns 0.
- Same as
+
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-add-int)[source]¶
- fn (unchecked-add-int x)
- fn (unchecked-add-int x y)
- fn (unchecked-add-int x y & args)
Sum the arguments together. If no arguments given, returns 0.
- Same as
+
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-dec x)[source]¶
Decrement the argument by 1.
- Same as
dec
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-dec-int x)[source]¶
Decrement the argument by 1.
- Same as
dec
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-divide-int x)[source]¶
- fn (unchecked-divide-int x y)
- fn (unchecked-divide-int x y & args)
Divide the arguments. If no arguments given, returns the inverse of the argument.
- Same as
/
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-double x)[source]¶
Coerce
x
to a float.Python does not differentiate between
float
anddouble
. Pythonfloat
s are double precision.- Same as
double
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-float x)[source]¶
Coerce
x
to afloat
.If
x
is string, it is parsed as a floating point number.- Same as
float
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-inc x)[source]¶
Increment the argument by 1.
- Same as
inc
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-inc-int x)[source]¶
Increment the argument by 1.
- Same as
inc
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-int x)[source]¶
Coerce
x
to anint
.If
x
is string, it is parsed as a base 10 number.- Same as
int
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-long x)[source]¶
Coerce
x
to anint
.Python does not support long types, so the value is coerced to an integer as by
int
.- Same as
long
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-multiply)[source]¶
- fn (unchecked-multiply x)
- fn (unchecked-multiply x y)
- fn (unchecked-multiply x y & args)
Multiply the arguments. If no arguments given, returns 1.
- Same as
*
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-multiply-int)[source]¶
- fn (unchecked-multiply-int x)
- fn (unchecked-multiply-int x y)
- fn (unchecked-multiply-int x y & args)
Multiply the arguments. If no arguments given, returns 1.
- Same as
*
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-negate x)[source]¶
Return the negation of
x
.Same as
(- x)
. Python integers are unlimited precision so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- fn (unchecked-negate-int x)[source]¶
Return the negation of
x
.Same as
(- x)
. Python integers are unlimited precision so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- fn (unchecked-short x)[source]¶
Coerce
x
to anint
.Python does not support short types, so the value is coerced to an integer as by
int
.- Same as
short
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- Same as
- fn (unchecked-subtract x)[source]¶
- fn (unchecked-subtract x y)
- fn (unchecked-subtract x y & args)
- Subtract the arguments. If one argument given, returns the negation of that
argument.
- Same as
-
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- fn (unchecked-subtract-int x)[source]¶
- fn (unchecked-subtract-int x y)
- fn (unchecked-subtract-int x y & args)
- Subtract the arguments. If one argument given, returns the negation of that
argument.
- Same as
-
. Python integers are unlimited precision, so unchecked arithmetic is only provided for compatibility with platforms without unlimited precision integers.
- fn (underive tag parent)[source]¶
- fn (underive h tag parent)
Remove a parent/child relationship between
tag
andparent
originally created viaderive
.tag
may be either a valid Python type or a namespace-qualified keyword or symbol.parent
must be a namespace-qualified keyword or symbol.h
must be a hierarchy returned bymake-hierarchy
. Ifh
is not supplied, the global hierarchy will be used.
- Var unquote¶
Placeholder Var so the compiler does not throw an error while syntax quoting.
See Macros and Syntax Quoting for more details.
- Var unquote-splicing¶
Placeholder Var so the compiler does not throw an error while syntax quoting.
See Macros and Syntax Quoting for more details.
- fn (unreduced x)[source]¶
If
x
is a reduced value (as produced byreduced
), unwrap it and return the inner value. Otherwise returnx
.
- fn (update m k f & args)[source]¶
Updates the value for key
k
in associative data structurem
with the return value from calling(f old-v & args)
. Ifm
isnil
, use an empty map. Ifk
is not inm
,old-v
will benil
.
- fn (update-in m ks f & args)[source]¶
Updates the value for key
k
in associative data structurem
with the return value from calling(f old-v & args)
. Ifm
isnil
, use an empty map. Ifk
is not inm
,old-v
will benil
.
- fn (update-keys m f)[source]¶
Update the keys in map
m
by applying a function of one argument,f
, to every key.f
must return a unique key for every input key, otherwise the behavior of this function is undefined.
- fn (update-vals m f)[source]¶
Update the values in map
m
by applying a function of one argument,f
, to every value.
- fn (use & args)[source]¶
Load Basilisp libraries and make them accessible in the current namespace.
Arguments should be libspecs, which take the following forms:
symbols, which name fully qualified namespaces
vectors, which take the form
[namespace-symbol & opts]
use
is likerequire
which also refers all Vars from the requiring Namespace afterwards. Libspecs passed touse
may include filters as defined inrefer
to narrow down the referred Vars.Supported filters:
:only [sym1 sym2]
to only refer the specified symbols:exclude [sym1, sym2]
to refer all except the specified symbols:rename {sym1 new-sym1}
to rename all the specified symbols to the given new name
Use of
use
directly is discouraged in favor of the:use
directive in thens
macro.
- fn (uuid-like? x)[source]¶
Return
true
ifx
is coercible to auuid.UUID
.Python’s UUID constructor supports byte sequences in big- and little-endian byte orders. This function checks only for big-endian bytes.
- fn (var-get v)[source]¶
Return the value inside the Var. Return thread local bindings if they exist, otherwise, return the root binding.
- fn (vary-meta o f & args)[source]¶
Return an object of the same type and representing the same value as
o
(as bywith-meta
) with the new object’s metadata set to the value of(apply f (meta o) & args)
.
- fn (vreset! v new-val)[source]¶
Reset the value of volatile
v
non-atomically tonew-val
. Returns the new value.
- fn (vswap! v f & args)[source]¶
Swap the value of volatile
v
non-atomically to the return of(apply f old-val args)
. Returns the new value of that function call.
- macro (when cond & body)[source]¶
Evaluate
cond
and if it is truthy, execute body in an implicitdo
block.
- macro (when-first binding & body)[source]¶
Evaluate the binding as with
let
, binding the given name to the first value (as byfirst
) in the binding expression iff the first value in the binding expression is notnil
. Returnnil
otherwise.
- macro (when-let binding & body)[source]¶
Evaluate the binding as with
let
, binding the given name for use in thetrue
expression iff the binding expression is truthy. Returnnil
otherwise.
- macro (when-not cond & body)[source]¶
Evaluate
cond
and if it is falsey, execute body in an implicitdo
block.
- macro (when-some binding & body)[source]¶
Evaluate the binding as with
let
, binding the given name for use in the true expression iff the binding expression is notnil
. Returnnil
otherwise.
- macro (while cond & body)[source]¶
Execute
body
repeatedly (likely for side effects) untilcond
returnsfalse
. Returnnil
.
- macro (with bindings & body)[source]¶
Evaluate
body
within atry
/except
expression, binding the named expressions as per Python’s context manager protocol spec (Python’swith
blocks).
- macro (with-bindings bindings-map & body)[source]¶
Execute the expressions given in the
body
with the thread-local Var bindings specified in the Var/value mapbindings-map
installed.The thread-local Var bindings will be popped after executing the body in all cases.
Returns the value of
body
.
- fn (with-bindings* bindings-map f & args)[source]¶
Execute the function
f
with the given argumentsargs
(as byapply
) with the thread-local Var bindings specified in the Var/value mapbindings-map
installed.The thread-local Var bindings will be popped after executing
f
in all cases.Returns the return value of
f
.
- macro (with-in-str s & body)[source]¶
Evaluate body with
*in*
bound to aio.StringIO
instance containing the strings
.
- fn (with-meta o meta)[source]¶
Return an object of the same type and representing the same value as
o
withmeta
as its metadata. Of Basilisp’s builtin types, only those implementing the interface IWithMeta supportwith-meta
.
- macro (with-open & args)[source]¶
Evaluate
body
within atry
/except
expression, binding the named expressions as per Python’s context manager protocol spec (Python’swith
blocks).
- macro (with-out-str & body)[source]¶
Capture the contents of text sent to
*out*
and return the contents as a string.
- macro (with-redefs bindings & body)[source]¶
Temporarily re-bind the given Var roots to the given values while executing the body, binding back to the original value afterwards.
Changes to the Var roots will be visible in all threads.
Note that Basilisp directly links Var references in compiled code by default for performance reasons. Direct linking can be disabled for all Vars during compilation by setting the
--use-var-indirection
compiler flag at startup. Direct linking can be disabled for individual Vars by setting the^:redef
meta flag where the Var isdef
‘ed.with-redefs
will throw an Exception if directly linked Vars are given in the bindings.
- fn (with-redefs-fn bindings-map f)[source]¶
Temporarily re-bind the given Var roots to the given values while executing the function
f
, binding back to the original value afterwards.Changes to the Var roots will be visible in all threads.
Note that Basilisp directly links Var references in compiled code by default for performance reasons. Direct linking can be disabled for all Vars during compilation by setting the
--use-var-indirection
compiler flag at startup. Direct linking can be disabled for individual Vars by setting the^:redef
meta flag where the Var isdef
‘ed.with-redefs-fn
will throw an Exception if directly linked Vars are given in the bindings.