basilisp.core¶
- fn (*)[source]¶
- fn (* x)
- fn (* x y)
- fn (* x y & args)
Multiply the arguments. If no arguments given, returns 1. If one argument is given, return that argument.
- 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}ornilotherwise.Note that this value will differ from
sys.argvsince 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-data-reader-fn*[source]¶
When no data reader is found for a tag and
*default-data-reader-fn*is non-nil, it will be called with two arguments, the tag and the value. If*default-data-reader-fn*isnil(the default), raise abasilisp.lang.compiler.SyntaxError.
- 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
prnandprintlnfunctions should flush the output stream after the last newline is written.Defaults to
true.
- dynamic Var *import-module*¶
If not
nil, corresponds to the module which is currently being imported.
- 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}ornilotherwise.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*¶
Limits the number of items printed per collection. If falsy, all items are shown. If set to an integer, only that many items are printed, with
...indicating more. By default, it isnil, meaning no limit.
- 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. If one argument is given, return that argument.
- 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
xthrough 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
xthrough theforms. Placesxin 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.
- fn (-mangle-py-field type-sym field-name)[source]¶
Implementation detail of
defrecordto support Python’s managled field names.
- 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 only one argument is given, returns the inverse of the argument.
- fn (< _)[source]¶
- fn (< x & args)
Return
trueif arguments are monotonically increasing, otherwisefalse.
- fn (= _)[source]¶
- fn (= x & args)
Return
trueifxandyare 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
trueif 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
wfidentified by the keykto 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
derefthe 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
oto the result of(apply f m args)wheremis the current metadata ofo.fshould 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. Returns the new value.Note
Due to Basilisp’s Direct Linking Optimization, changes to a Var’s root value may not be reflected in the code unless the Var is dynamic. To ensure updates propagate, set the Var’s ^:redef metadata, which disables direct linking.
- macro (amap array idx ret expr)[source]¶
Map
exprover the Python listarray, returning a new Python list with the result.This macro initially binds the symbol named by
retto a clone ofarray. On each iteration, the index (named byidx) ofretis 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
tagin hierarchyh.tagmay be either a valid Python type or a namespace-qualified keyword or symbol. Iftagis a Python type, ancestors include any relationships established via calls toderiveas well as any superclasses (as returned bysupers). Iftagis a namespace-qualified keyword, only relationships fromderiveare returned.hmust be a hierarchy returned bymake-hierarchy. Ifhis 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
andwith no arguments returnstrue.
- fn (apply f & args)[source]¶
Apply function
fto the arguments provided.The last argument must always be coercible to a Seq. Intermediate arguments are not modified. The Seq in the last argument may be infinite if the called function
fis lazy.Warning
Applying arguments to Python functions (rather than Basilisp functions) will consume the argument Seq eagerly. Infinite Seqs are not supported for Python functions.
- fn (apply-kw f & args)[source]¶
Apply function
fto 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 (apply-method-kw o method & args)[source]¶
Apply keyword arguments to a method call. Equivalent to
(apply-kw (.-method o) ... args).
- macro (areduce array idx ret init expr)[source]¶
Reduce the Python list
arraybyexpr, returning the reduced expression.This macro initially binds the symbol named by
rettoinit. On each iteration,retis rebound to the return value ofexpr.
- macro (as-> x name & forms)[source]¶
Bind
xto name and thread it through theforms, replacing instances ofnamein 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 (aslice array & stop-or-start-stop-step)[source]¶
Get a portion of the Python list
arrayusing a Pythonsliceinstance with a singlestopvalue, or a combination ofstartandstopand optionalstepvalues.Equivalent to Python’s
array[start:stop:step]extended indexing syntax. Usenilwhen omitting any of these fields.
- macro (assert expr)[source]¶
- macro (assert expr message)
Evaluate
exprand 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. Ifmisnil, 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
ksas a sequence of keys andvas the new value. If no map exists for any key inks, a new empty map will be created.
- fn (associative? x)[source]¶
Return
trueifximplementsbasilisp.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 byderefing 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
xto a Pythondecimal.Decimal.
- fn (bigint x)[source]¶
Coerce
xto an integer.Python’s builtin
inttype is arbitrary precision, so there is no difference betweenbigint,biginteger, and Python’s builtinint.
- fn (biginteger x)[source]¶
Coerce
xto an integer.Python’s builtin
inttype 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
xto a boolean.Only
falseandnilare 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
fnwhen defining a function) which will be executed with the same thread-local Var bindings as were in effect whenbound-fnwas 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
fwith the same thread-local Var bindings as were in effect whenbound-fn*was called.fwill 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 anycollfor whichcounted?returnstrue, otherwise return the lesser ofnand the length ofcoll.
- fn (byte-string x)[source]¶
- fn (byte-string x encoding)
- fn (byte-string x encoding errors)
Coerce
xto a byte string (Pythonbytesobject).Arguments shall be interpreted exactly as with that object’s constructor.
- fn (byte-string? x)[source]¶
Return
trueifxis a byte string (the Pythonbytestype).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
bytarrayandbytestypes).This function is provided for Clojure compatibility.
- fn (bytes? x)[source]¶
Return
trueifxis a byte array (the Pythonbytearraytype).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
xis a Pythonbytearray. To check if an object is a Pythonbytes, usebyte-string?.
- macro (case expr & clauses)[source]¶
Switch on
exprto 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
xto 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.
- Var char-escape-string[source]¶
Return the escape string for an escape character, or
nilif the provided character is not an escape character.
- Var char-name-string[source]¶
Return the name of an escape character, or
nilif the provided character is not an escape character.
- fn (chars x)[source]¶
Dummy cast to a Python list of chars.
This function is provided for Clojure compatibility.
- fn (coll? x)[source]¶
Return
trueifximplementsbasilisp.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
xandy.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.nilcompares less than all values except itself.NaNcompares 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
atomtonew-valif and only ifold-valis 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 tofwith no arguments. The 1-arity will callcfon its argument. The 2-arity will callfdirectly with both of its arguments.If
cfis not given,identitywill 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 thecondpexpression.Clauses can take two forms:
test-expr result-exprtest-expr :>> result-fnwhere :>> is a keyword literal
For the ternary expression clause, the unary
result-fnwill be called with the result of the predicate.A single final expression can be included at the end with no test expression which will be returned if no other clause matches the predicate. If no default is provided and no clause matches the predicate, a
ValueErrorwill be thrown.
- fn (conj)[source]¶
- fn (conj coll)
- fn (conj coll x)
- fn (conj coll x & xs)
Conjoin
xsto collectioncoll. New elements may be added in different positions depending on the type ofcoll.conjreturns the same type ascoll. Ifcollisnil, return a list withxsconjoined.
- fn (conj!)[source]¶
- fn (conj! coll)
- fn (conj! coll & xs)
Conjoin
xsto 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
ois the first element andseqis the rest. Ifseqis nil, return a list containingo. Ifseqis not a Seq, attempt to coerce it to a Seq and then consoonto the resulting sequence.
- fn (construct-proxy c & ctor-args)[source]¶
Construct an instance of the proxy class
cwith the given constructor arguments.Throws an exception if
cis not a subclass ofbasilisp.lang.interfaces.IProxy.Note
In JVM Clojure, this function is useful for selecting a specific constructor based on argument count, but Python does not support multi-arity methods (including constructors), so this is likely of limited use.
- fn (contains? coll k)[source]¶
Return
trueifcollcontainsk. For vectors,kis an index. For maps,kis a key. For sets,kis a value in the set.
- fn (count coll)[source]¶
Return the length of
collas by Python’slenbuiltin, or 0 ifcollis 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-symor return the existing one if it already exists.
- fn (dec' x)[source]¶
Decrement the argument by 1.
Included for Clojure compatibility. Functionally identical to
dec.
- fn (decimal? x)[source]¶
Return
trueifxis adecimal.Decimal.
- macro (declare & names)[source]¶
Declare the given
namesas 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 defs.
- 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 ...]).selforthisarguments 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.ABCand all method definitions are declared asabc.abstractmethod()s and thus must be implemented by a concrete type.Interfaces created by
definterfacecannot 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
defmacroare 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
defmacrohave access to two implicit arguments whose names must not appear in your argument list:&envis a map of all symbol bindings available to the compiler at the point the macro is invoked.&formis 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
multifnwhich responds todispatch-val.fn-tailis the trailing part of a function definition afterfnincluding any relevant argument vectors.Methods added to a multimethod can be removed using
remove-method. All methods may be removed usingremove-all-methods.See
defmultifor more information about multimethods.
- macro (defmulti name & body)[source]¶
Define a new multimethod with the given
nameand abodyconsisting 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
defmethodmacro.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-methodor aRuntimeExceptionwill 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, overriding any existing metadata associated with the
name.A few special meta keys change how
defnemits the final Var and function. The processing is handled byfn::decoratorsis an optional vector of functions which will wrap the final function emitted bydefn. Like standard Python decorators and thecompfunction, 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:privatemetadata, which makes them ineligible for access outside the namespace usingrequireorrefer.
- macro (defonce name expr)[source]¶
Define the Var named by
namewith root binding set toexprif and only if anameis not already defined as a Var in this namespace.exprwill 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
selfargument).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
selforthisarguments 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
objectare not required to implement allobjectmethods.Method declarations should appear as:
(method-name [arg1] & body) (method-name [arg1 arg2 ...] & body)
Records objects are created with sensible
objectdefaults as byattrs. New records may overrideobjectdefaults. 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->NewRecordwhich can be used to generate new instances of the record.Methods must supply a
thisorselfparameter.recurspecial 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
:mutablemetadata. 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
objectare not required to implement allobjectmethods.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
:applyor:collectstrategy on the:kwargsmetadata on the method name. Methods may be declared as static (using the:staticmethodmeta key) or class methods (using the:classmethodmeta 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:propertymetadata 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
objectdefaults as byattrs. New types may overrideobjectdefaults. 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->NewTypewhich can be used to generate new instances of the type.Methods must supply a
thisorselfparameter.recurspecial forms used in the body of a method should not include that parameter, as it will be supplied automatically.Note
deftypecreates new types with__slots__by default. To disable usage of__slots__, provide the^{:slots false}meta key on the type name.(deftype ^{:slots false} Point [x y z])
- macro (delay & body)[source]¶
Takes a body of expressions producing any value. Will not produce a value until
derefed. The result is cached and returned in futurederefs.
- fn (deliver p v)[source]¶
Deliver the value
vto the promisep. Ifpalready has a value, then a subsequent call todeliverforpwill have no effect.
- fn (deref o)[source]¶
- fn (deref o timeout-ms timeout-val)
Dereference a delay, atom, promise, future, volatile, or Var and returns its contents.
If
ois an object implementingbasilisp.lang.interfaces.IBlockingDeref(i.e. futures and promises) andtimeout-msandtimeout-valare supplied,derefwill wait at mosttimeout-msmilliseconds, returningtimeout-valiftimeout-msmilliseconds elapse andohas not returned.
- fn (derive tag parent)[source]¶
- fn (derive h tag parent)
Derive a parent/child relationship between
tagandparent.tagmay be either a valid Python type or a namespace-qualified keyword or symbol.parentmust be a namespace-qualified keyword or symbol.hmust be a hierarchy returned bymake-hierarchy. Ifhis 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
tagin hierarchyh.tagmust be a namespace-qualified keyword or symbol. Python types are not supported fordescendantschecks.hmust be a hierarchy returned bymake-hierarchy. Ifhis not supplied, the global hierarchy will be used.
- fn (destructure [binding expr])[source]¶
Take a
[binding expr]pair (as from aletblock) 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
swithout 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
swithout 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
mwithout 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
mwithout 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
formacro. 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
xand 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
xto a float.Python does not differentiate between
floatanddouble. Pythonfloats are double precision.
- fn (double? & args)[source]¶
Return
trueifois afloat.Same as
float?. Python does not distinguish between single and double precision floating point numbers, so all floating points are calledfloatand 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
nelements ofcoll.Return a stateful transducer if no collection is provided.
- fn (drop-while pred)[source]¶
- fn (drop-while pred coll)
Drop elements of
colluntil(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 tocompin the given order.Unlike with
sequence,eductionreturns 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,
sequenceis preferred.
- fn (empty? coll)[source]¶
Return
trueifcollis empty (as by(not (seq coll))).Typically, you should prefer the idiom
(seq coll)to(not (empty? coll)).
- fn (ensure-reduced x)[source]¶
If
xis 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
namespaceis 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
trueif all input predicates returntruefor a value, otherwise returnsfalse. The returned predicate returnsfalseon the first failing predicate and will not execute any remaining predicates.
- fn (ex-cause ex)[source]¶
Return the cause (another Exception) of
exif it derives fromException, otherwise it returnsnil.
- fn (ex-data ex)[source]¶
Return the data map of
exif is an instance ofbasilisp.lang.interfaces.IExceptionInfo, otherwise it returnsnil.
- fn (ex-info msg data)[source]¶
Returns a
basilisp.lang.exception/ExceptionInfoinstance 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-typeshould 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-typeis 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+methodsare 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.extendmay be called multiple times for a singletarget-type, so not all implementations need to be known a priori. Successive calls toextendontarget-typewith the same Protocol implementations will overwrite previous implementations.If you are extending types with explicit function definitions, the
extend-protocolandextend-typemacros 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
extenddirectly.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
extendcalls:(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
extenddirectly.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
extendcall:(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
deftypeanddefrecord). Only types extending proto viaextend(orextend-protocolorextend-type) will appear.
- fn (extends? {:as proto, :keys [interface impls]} type)[source]¶
Return
trueiftype extends protocolproto.
- fn (file-seq dir)[source]¶
Return a seq of
pathlib.Pathobjects for all files and subdirectories ofdir.
- fn (filter pred)[source]¶
- fn (filter pred coll)
Return a lazy sequence of elements from
collwhere(pred elem)returns a truthy value.Return a transducer if no collection is provided.
- fn (filterv & args)[source]¶
Return a vector of elements from
collwhere(pred elem)returns a truthy value.
- fn (find-keyword name)[source]¶
- fn (find-keyword ns name)
Return the keyword named by
nameand optionallynsif it has already been interned.Return
nilotherwise.
- fn (find-var sym)[source]¶
Return the Var named by namespace-qualified
symif it exists, ornilotherwise.
- fn (first seq)[source]¶
If
seqis a Seq, return the first element fromseq. Ifseqisnil, returnnil. Otherwise, coercesseqto 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
flattenon 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.
A few special metadata keys change how
fnemits the final function::decoratorsis an optional vector of functions which will wrap the final function emitted byfn. Like standard Python decorators and thecompfunction, decorators are applied to the generated function from right to left.
Note
The
namemetadata (i.e.,(fn ^{...} <name> ...)) takes precedence over theformmetadata (i.e.,^{...} (fn <name?> ...)) when both specify the same key.Function argument vectors support sequential and associative Destructuring .
See
fnfor more details.
- fn (fnil f x)[source]¶
- fn (fnil f x y)
- fn (fnil f x y z)
Given a function
f, return a new function which replaces anilfirst argument with the valuex. Higher arity variants will replace their correspondingnilargument with the provided default value for that argument position.The function returned from
fnilsupports any number of arguments greater than or equal to the arity of thefnilthat is called.
- 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
doblock.Symbol bindings look like standard
letbindings. Values bound to symbols should be sequences or otherwise seqable. The body of theforcomprehension 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 nestedforloops 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]: :letbindings work like any standard let bindings; destructuring is permitted; may refer to any previous bindings in other:letmodifiers or normal symbol bindings. Multiple pairs of bindings may appear in:letbindings.- keyword
:when expr: :whenbindings are applied to the sequence roughly like in the corefilterfunction; the expression is evaluated and if it is not falsey, yield the next value. As with:letbindings, the expression may refer to any previously bound names.- keyword
:while expr: :whilebindings terminate the current sequence at the first point whenexprreturns a falsey value.:whilebindings 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
- macro (for-async binding & body)[source]¶
Repeatedly execute
bodywhile the binding name is repeatedly rebound to successive values from the asynchronous iterable.Warning
The
for-asyncmacro may only be used in an asynchronous function context.
- fn (force x)[source]¶
If
xis a Delay, returned the possibly cached value ofx. Otherwise, returnx.
- fn (frequencies coll)[source]¶
Return a map whose keys are the elements of
colland whose values are the counts for the number of times the key appears incoll.
- macro (future & body)[source]¶
Execute the expressions of
bodyin another thread. Returns a Future object. The value returned by the body can be fetched usingderefor@, though doing so may block unless thederefwith a timeout argument is used.
- fn (future-call f)[source]¶
- fn (future-call f pool)
Call the no args function
fin another thread. Returns a Future object. The value returned byfcan be fetched usingderefor@, though doing so may block unless thederefwith 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
trueif the Futurefuthas been cancelled,falseotherwise.
- 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
selforthis, like:[ (method-name [args ...] docstring) ... ]
Callers should use
definterfaceto generate new interfaces.- keyword
- fn (gensym)[source]¶
- fn (gensym prefix)
Generate a unique symbol name of the form
prefix_#. If noprefixis given, thenv_will be used.
- fn (get m k)[source]¶
- fn (get m k default)
Return the entry of
mcorresponding tokif it exists ornilordefault(if specified) otherwise.mmay be any associative type (such as a vector or map), set type, or string. Ifmis not one of the supported types,getalways returnsnilordefault(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
ksordefault(default:nil) if the value is not found.If
ksis empty, returnm.
- fn (get-method multifn dispatch-val)[source]¶
Return the method of multimethod
multifnwhich would respond todispatch-valornilif no method exists fordispatch-val.
- fn (get-proxy-class & bases)[source]¶
Given zero or more base classes, return a proxy class for the given classes.
If no classes, Python’s
objectwill be used as the superclass.Generated classes are cached, such that the same set of base classes will always return the same resulting proxy class.
- 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
nilif no validator is defined.
- fn (group-by f coll)[source]¶
Return a map whose keys are the result of calling
fon each element incolland 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
predreturns a truthy value for an input.If
retfis 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 callingretfwill be the return value of the transducer.If
retfis not given, the defaultretfwill 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 thetrueexpression iff the binding expression is truthy . Otherwise, return thefalseexpression without binding the name.
- macro (if-not cond true-cond false-cond)[source]¶
Evaluate
condand 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 thetrueexpression iff the binding expression is notnil. Otherwise, return thefalseexpression without binding the name.
- fn (ifn? x)[source]¶
Return
trueifxis 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 & opts]. Theoptsshould be pairs of a keyword and a value from below, similar toimport::as namewhich will alias the imported module to the symbol name:refer [& syms]which will refer module members in the local namespace directly:refer :allwhich will refer all module members from the namespace directly
Note that unlike in Python,
imported Python module names are always hoisted to the current Namespace, so imported names will be available within a Namespace even if theimportitself occurs within a function or method.Use of
importdirectly is discouraged in favor of the:importdirective in thensmacro.Importing and attempting to reference an import within a top level form other than a
dois a compile-time error because the compiler cannot verify that the imported name exists. In cases where you may need to import and reference an imported symbol within a single top-level form, you can useimporting-resolve.
- fn (importing-resolve sym)[source]¶
Resolve the namespaced symbol
symas a Python module member. If resolution fails, attempts to importsym‘s namespace (as byimport) before resolving again.
- fn (in-ns & args)¶
- fn (inc' x)[source]¶
Increment the argument by 1.
Included for Clojure compatibility. Functionally identical to
inc.
- fn (init-proxy proxy mappings)[source]¶
Set the current proxy method map for the given proxy.
Method maps are maps of string method names to their implementations as Basilisp functions.
Throws an exception if
proxyis not a proxy.
- fn (inst-ms inst)[source]¶
Return the number of milliseconds since the Unix epoch (January 1, 1970 00:00:00 UTC) as an integer.
- fn (int? & args)[source]¶
Return
trueifxis 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
collseparated bysep. Ifcollis 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
fromto the existing to collectionto, as byconj.A transducer may be provided as
xformto transform the elements as they are copied.intowill 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
tagis equal toparentor is a descendant ofparentin hierarchyh.Both
tagandparentmay be a valid Python type or a namespace-qualified keyword or symbol or a vector of namespace-qualified keywords or symbols. If either oftagorparentis a vector, the other must be a vector as well.Ancestors will be fetched for
tagusingancestors.hmust be a hierarchy returned bymake-hierarchy. Ifhis not supplied, the global hierarchy will be used.
- fn (iteration step & {:keys [somef vf kf initk], :or {kf identity, vf identity, initk nil, somef some?}})[source]¶
Return a reducible sequence via repeated calls to
step, a function of a “continuation token”,k.stepwill 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 neitherkfnorvfwill be called. If the iteration continues,stepwill be called again with the result of(kf ret).Only
stepis a required argument.somefdefaults tosome?,vfandkfdefault toidentity, andinitkdefaults tonil.For the purposes of this function,
stepshould be considered an impure function and repeated calls to it even with the same token may not necesarily return the same values.
- fn (iterator-seq it)[source]¶
Coerce the python Iterable
itto a Seq. Supports both re-iterable (as withseq) as well as single-use iterables that always return the same iterator.
- 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-
nilresults 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-
nilresults of(f index elem)for elements incoll.Return a stateful transducer if no collection is provided.
- fn (keys m)[source]¶
Return a seq of the keys from a map-like object.
If
misnil, returnnil.If
mis castable to a seq, cast it to a seq and callkeyson that.If
mis a seq, yield the keys from successive entries (which must be map entries).If
mis any type of mapping, return a seq of that mapping’s keys.
- fn (keyword name)[source]¶
- fn (keyword ns name)
Create a new keyword with
nameand optional namespacens. Keywords will have the colon prefix added automatically, so it should not be provided.namemay be keyword, symbol, or string. Ifnameis a keyword or symbol with a namespace, the namespace will be included in the resulting value. Ifnameis a string with at least one ‘/’, the string will be split on the first ‘/’ character with the first segment being used asnsand the second asname.If
nsis notnil, then bothnameandnsmust 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. Whenseqis first called on the resultinglazy-seq, the sequence will be realized.
- macro (let bindings & body)[source]¶
letbindings 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
letfnbindings may refer to each other regardless of their order of definition.See
letfnfor more details.
- fn (lisp->py o)[source]¶
- fn (lisp->py o & {:keys [keyword-fn], :or {keyword-fn name}})
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-fnis 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.
requirewill try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario).loadwill 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 byloadwill 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-readerorload-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.
requirewill try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario).load-filewill load the contents of the named file directly into the current namespace.Note that unlike
require, files loaded byload-filewill 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.TextIOBaseinstancereader.Most often this is useful if you want to split your namespace across multiple source files.
requirewill try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario).load-readerwill load the contents of the named file directly into the current namespace.Note that unlike
require, files loaded byload-readerwill 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
nsmacro.
- fn (local-decimal-context precision)[source]¶
- fn (local-decimal-context precision rounding)
Return a
decimal.localcontext()context manager which sets the precision and rounding behavior ofdecimal.Decimalinstances in the current thread as bydecimal.setcontext().Warning
This function is an implementation detail of
with-precisionand it is not considered part of the public API. Use at your own peril.
- fn (long x)[source]¶
Coerce
xto 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]¶
loopbindings with Destructuring support.
- fn (macroexpand form)[source]¶
Repeatedly macroexpand
formas bymacroexpand-1until form no longer represents a macro. Returns the expanded form. Does not macroexpand child forms.
- fn (macroexpand-1 form)[source]¶
Macroexpand
formone 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
typeargument 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 functionfwill 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
keyandvalue.
- fn (map-entry? x)[source]¶
Return
trueifximplementsbasilisp.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 & colls)
Return a lazy sequence of the concatenated results of mapping
fovercolls.
- 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 functionfwill 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
nameon the first argument of the resulting function. Ifargsare 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
numanddiv.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
nameprior 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
classwithargs.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
newkeyword for object instantiation.
- fn (next seq)[source]¶
Calls
restono. Iforeturns 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
:dockey on the namespace metadata map.An optional map of metadata can be given after the docstring. If provided, this metadata will be merged into the metadata for the resulting namespace.
Example:
(ns my.namespace "My namespace with code" {:meta-key 1} (: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-clojureis also accepted) controls how names frombasilisp.coreare exposed in the namespace. Refer toreferfor usage.:requireimports other Basilisp namespaces. Refer torequirefor usage.:useis a variant of:require, although:requireis preferred in most cases. Seeusefor usage.:importimports Python modules and packages. Refer toimportfor usage.
Use of the
nsmacro to control requires and imports is recommended in all cases. The various functions thatnsdelegates 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-import-refers ns)[source]¶
Return a set of Python module members which are referred 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,ns-refers, andns-importsin one map.Note
It is possible that the same symbol is mapped to an interned name, a referred name, an imported name, or an import-referred name. They are stored in separate collections in each namespace and Basilisp symbol resolution rules determine the precedence. This function returns the combined set of all mapped symbols in a single map and therefore symbols defined in multiple maps will only show one value. Inspecting the contents of each of the component maps will show all mappings, including those that were overwritten by the merge operation in this function.
- 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
:privatemetadata.
- 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
ith element ofcoll(0-indexed), if it exists ornilotherwise. Ifiis out of bounds, throws anIndexErrorunlessnotfoundis specified.collmay be any sequential collection type (such as a list or vector), string, ornil. Ifcollis not one of the supported types, aTypeErrorwill 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, orcollifiis 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-seqand is aseqyielding fewer thansizeelements, then the remaining indices of the resulting array will be filled withnilvalues.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
orwith no arguments returnsnil.
- fn (parents tag)[source]¶
- fn (parents h tag)
Return the set of all direct parents of
tagin hierarchyh.tagmay be either a valid Python type or a namespace-qualified keyword or symbol. Iftagis a Python type, ancestors include any relationships established via calls toderiveas well as any immediate superclasses (as returned bybases). Iftagis a namespace-qualified keyword, only relationships fromderiveare returned.hmust be a hierarchy returned bymake-hierarchy. Ifhis not supplied, the global hierarchy will be used.
- fn (parse-boolean s)[source]¶
Parse the string argument
sas either booleantrueorfalsereturning the boolean if the string contains one, ornilotherwise.This function will throw a
TypeErrorfor non-string types.
- fn (parse-double s)[source]¶
Parse the string argument
sas a floating point number as by Python’s builtinfloatfunction, returning the float if the string contains one, ornilotherwise.This function will throw a
TypeErrorfor non-string types.
- fn (parse-long s)[source]¶
Parse the string argument
sas an integer (base 10) as by Python’s builtinintfunction, returning the integer if the string contains one, ornilotherwise.This function will throw a
TypeErrorfor non-string types.
- fn (parse-uuid s)[source]¶
Parse the string argument
sas auuid.UUID, returning the UUID if the string contains one, ornilotherwise.This function will throw a
TypeErrorfor non-string types.
- fn (partial f)[source]¶
- fn (partial f & args)
Return a function which is the partial application of
fwithargs.
- 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
fwith 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 (vianame), 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
collof sizenat offsets ofstepelements. Ifstepis not given, steps of sizenwill be used and there will be no overlap between partitions. Ifpadis given, partition will pull elements frompaduntil the final sequence is equal to sizen. If there are fewer thannleftover 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
collof sizenat offsets ofstepelements. Ifstepis not given, steps of sizenwill be used and there will be no overlap between partitions. If there are leftover elements fromcollwhich 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
colleach timefreturns 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
collwhich was created by callingtransient.
- fn (pmap f coll)[source]¶
- fn (pmap f coll & colls)
Apply
fas 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 whenpmapis 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
collis empty, throw an exception.
- fn (pop! coll)[source]¶
Return a new transient vector without the last element of
coll. Ifcollis 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 (as byrepr). 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
multifnto preferdispatch-val-xoverdispatch-val-yin 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.printlnalways 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?.
- macro (proxy class-and-interfaces args & fs)[source]¶
Create a new proxy class instance.
The proxy class may implement 0 or more interface (or subclass 0 or more classes), which are given as the vector
class-and-interfaces. If 0 such supertypes are provided, Python’sobjecttype will be used.If the supertype constructors take arguments, those arguments are given in the potentially empty vector
args.The remaining forms (if any) should be method overrides for any methods of the declared classes and interfaces. Not every method needs to be overridden. Override declarations may be multi-arity to simulate multi-arity methods. Overrides need not include
this, as it will be automatically added and is available within all proxy methods. Proxy methods may access the proxy superclass using theproxy-supermacro.Overrides take the following form:
(single-arity [] ...) (multi-arity ([] ...) ([arg1] ...) ([arg1 & others] ...))
Note
Proxy override methods can be defined with Python keyword argument support since they are just standard Basilisp functions. See Basilisp Functions with Keyword Arguments for more information.
Warning
The
proxymacro does not verify that the provided override implementations arities match those of the method being overridden.Warning
Attempting to create a proxy with multiple superclasses defined with
__slots__may fail with aTypeError. If you control any of the designated superclasses, removing conflicting__slots__should enable creation of the proxy type.
- fn (proxy-mappings proxy)[source]¶
Return the current method map for the given proxy.
Throws an exception if
proxyis not a proxy.
- macro (proxy-super meth & args)[source]¶
Macro which expands to a call to the method named
methon the superclass with the providedargs.Note this macro explicitly captures the implicit
thisparameter added to proxy methods.
- 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-bindingscall in atry/finallyblock.This function is a very low level function and its use is discouraged in favor of a higher level construct like the
bindingmacro.
- 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 & {:keys [keywordize-keys], :or {keywordize-keys true}})
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 Pythondictswill be converted into keywords in the final return value.
- fn (quot num div)[source]¶
Returns the quotient of
numanddiv.The division result is rounded towards zero.
- 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) andupperinclusive.
- fn (random-sample prob)[source]¶
- fn (random-sample prob coll)
Return elements from
collwith 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. Ifendis specified, the sequence will terminate atend. Ifstepis specified, that amount will be added for each iteration.stepmay be negative.
- fn (ratio? x)[source]¶
Return
trueifxis afractions.Fraction.
- fn (rationalize num)[source]¶
- fn (rationalize num max-denominator)
Return the lowest ratio of
num.If
numis an integer or simplifies to an integer, return that value.If
max-denominatoris notnil, return an approximate rationalization fornumwith denominator at mostmax-denominator. Default is 1000000.
- 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.Patterninstance.
- 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*or a default data reader function to :lpy:var::*default-data-reader-fn* to customize the data readers used reading this stringThe stream must satisfy the interface of
io.TextIOBase, but does not require any pushback capabilities. The defaultbasilisp.lang.reader.StreamReadercan wrap any object implementingTextIOBaseand provide pushback capabilities.
- fn (read-seq stream)[source]¶
- fn (read-seq opts stream)
Create an lazy sequence that will contain each form from the
stream. If no stream is specified, uses the value currently bound to*in*. It is the callers responsibility to ensure that the stream resource is not closed before the sequence has been realised.Callers may bind a map of readers to
*data-readers*to customize the data readers used reading this stringThe stream must satisfy the interface of
io.TextIOBase, but does not require any pushback capabilities. The defaultbasilisp.lang.reader.StreamReadercan wrap any object implementingTextIOBaseand provide pushback capabilities.optsmay include, among other things, the following keys:- Parameters:
:init-line – optional initial line number for reader metadata; helpful for contextualizing errors for chunks of code read from a larger source document.
:init-column – optional initial column number for reader metadata; helpful for contextualizing errors for chunks of code read from a larger source document.
- 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-stringshould not be used to read string input from untrusted sources. For reading EDN input from untrusted sources, instead consider usingbasilisp.edn.
- fn (reader-conditional form is-splicing?)[source]¶
Construct a data representation of a reader conditional.
The form must contain balanced key-value pairs.
- fn (reader-conditional? o)[source]¶
Return true if the value is the data representation of a reader conditional.
- fn (realized? o)[source]¶
Return
trueif the delay, future, lazy sequence, or promise has been realized.
- fn (reduce f coll)[source]¶
- fn (reduce f val coll)
Reduce
collbyf.If
valis not supplied andcollhas no elements,fwill be called with no arguments and the result will be returned.If
valis not supplied andcollhas one element, the result of(f (first val))is returned.If
valis not supplied andcollhas elements, repeatedly reducecollby callingfon successive elements incoll.If
valis supplied andcollhas no elements, returnval` and ``fwill not be called.If
valis supplied andcollhas elements, repeatedly reducecollby callingfon successive elements incoll, starting withval.If
freturns areducedvalue at any point, reduction will terminate and the reduced value will be returned immediately.
- fn (reduce-kv f init coll)[source]¶
Reduce an associative
collbyf.fmust 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
collhas no elements,initis returned andfis not called.If
freturns areducedvalue at any point, reduction will terminate and the reduced value will be returned immediately.reduce-kvmay reduce vectors in addition to maps. Vectors have non-negative integer keys.
- fn (reduced x)[source]¶
Wraps a value
xsuch that it will terminate a reduce operation.Callers can retrieve the inner reduced value using
derefor@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
referdirectly is discouraged in favor of the:refermodifier in the:requiredirective of thensmacro or the:usedirective of thensmacro.
- fn (refer-basilisp & args)[source]¶
Refer Vars from
basilisp.coreusing 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,reifyreturns an object which implements the named interfaces using the implementations provided. You may not provide fields as such toreify, thoughreifycloses 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
objectare not required to implement allobjectmethods.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
:applyor:collectstrategy on the:kwargsmetadata on the method name. Finally, single-arity methods may be declared as Python properties using the:propertymetadata 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.reifydoes not support class method or static method members and attempting to declarereifymembers as class or static members will result in a compile time error.Type objects are created with sensible
objectdefaults as byattrs. New types may overrideobjectdefaults.Reified objects always implement
basilisp.lang.interfaces/IWithMetaand transfer the metadata from the form to the created object.Methods must supply a
thisorselfparameter.recurspecial forms used in the body of a method should not include that parameter, as it will be supplied automatically.
- fn (remove pred)[source]¶
- fn (remove pred coll)
Return elements from
collwhere(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
multifnwhich 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
nilin all cases.
- fn (remove-watch ref k)[source]¶
Remove the watch function identified by
kfrom the ref (Atom or Var), if it exists. Returns the ref.
- fn (repeat x)[source]¶
- fn (repeat n x)
Repeat
xinfinitely ornmany times ifnis specified. Returns a lazy sequence of thex.
- fn (repeatedly f)[source]¶
- fn (repeatedly n f)
Call
finfinitely ornmany times ifnis specified. Returns a lazy sequence of the return values.
- fn (replace smap)[source]¶
- fn (replace smap coll)
Replace elements of the vector/seq
collwith 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 namewhich will alias the imported namespace to the symbol name:as-alias namewhich 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 :allwhich will refer all symbols from the namespace directly
Arguments may also be flags, which are optional. Flags are keywords. The following flags are supported:
:reloadif provided, attempt to reload the namespace:reload-allif provided, attempt to reload all named namespaces and the namespaces loaded by those namespaces as a directed graph
Use of
requiredirectly is discouraged in favor of the:requiredirective in thensmacro.Requiring and attempting to reference a required namespace within a top level form other than a
dois a compile-time error because the compiler cannot verify that the required name exists. In cases where you may need to require and reference a required symbol within a single top-level form, you can userequiring-resolve.Warning
Reloading namespaces has many of the same limitations described for
importlib.reload(). Below is a non-exhaustive set of limitations of reloading Basilisp namespace:Vars will be re-
def’ed based on the current definition of the underlying file. If the file has not changed, then the namespace file will be reloaded according to the current Namespace Caching settings. If a Var is removed from the source file, it will not be removed or updated by a reload.References to objects from previous versions of modules (particularly those external to the namespace) are not rebound by reloading. In Basilisp code, this problem can be limited by disabling Inlining and Direct Linking.
Updates to type or record definitions will not be reflected to previously instantiated objects of those types.
- fn (requiring-resolve sym)[source]¶
Resolve the namespaced symbol
symas 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
vwithout regard to the previous value. Return the new value.
- fn (reset-meta! o meta)[source]¶
Atomically swap the metadata on reference
oto meta. References include atoms, namespaces, and vars.
- fn (reset-vals! atom v)[source]¶
Reset the value of an atom to
vwithout 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
seqis a Seq, return the elements after the first inseq. Ifseqisnil, returns an empty seq. Otherwise, coercesseqto a seq and returns the rest.
- fn (reverse coll)[source]¶
Return a seq containing the elements in
collin reverse order. The returned sequence is not lazy.
- fn (reversible? x)[source]¶
Return
trueif x implementsbasilisp.lang.interfaces.IReversible.
- fn (rseq coll)[source]¶
Return a sequence of the elements of
collin reverse order in constant time. Only Vectors support this operation.
- fn (run! proc coll)[source]¶
Runs the procedure
(proc elem)for each element incoll(presumably for side-effects) as byreduce.Returns
nilin all cases.
- fn (satisfies? {:as proto, :keys [interface impls]} x)[source]¶
Return true if
xsatisfies protocolproto.
- fn (sequence coll)[source]¶
- fn (sequence xform coll)
- fn (sequence xform coll & colls)
Coerces
collto a possibly empty sequence. Ifcollisnil, return().When a transducer
xformis supplied, returns a lazy sequence of the transform to elements ofcoll. If multiple collections are provided,xformmust 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
trueifximplementsbasilisp.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.
nilmay 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
xto 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/readerinstance onfand read the contents offinto 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:encodingoption.If
fis 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
xthrough the forms (as by->) until the resulting expression isnilor there are no more forms.
- macro (some->> x & forms)[source]¶
Thread
xthrough the forms (as by->>) until the resulting expression isnilor 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
collusing thecmpcomparator.The
comparefn is used in ifcmpis not provided.
- fn (sort-by keyfn coll)[source]¶
- fn (sort-by keyfn cmp coll)
Return a sorted sequence of the elements from
collusing thecmpcomparator on (keyfnitem).The
comparefn is used in ifcmpis not provided.
- fn (spit f content & opts)[source]¶
Open a
basilisp.io/writerinstance onfand writecontentout tofbefore 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:encodingoption.If
fis 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.spitdoes not support writing to non-file URLs.Return
nil.
- fn (split-at n coll)[source]¶
Split a collection at the
nth 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
ois 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
clshave been garbage collected.
- fn (subs s start)[source]¶
- fn (subs s start end)
Return a substring of
sfrom the indexstart(inclusive) to indexendexclusive, or the end of the string if noendis supplied.
- fn (subvec v start)[source]¶
- fn (subvec v start end)
Return a vector of elements consisting of the elements of
vfrom the indexstart(inclusive) to indexendexclusive, or the end of the vector if noendis supplied.
- fn (supers cls)[source]¶
Return the direct and indirect superclasses and interfaces of
clsas 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 functionfmay 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 functionfmay 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
nameand optional namespacens.namemay be keyword, symbol, string, or Var. Ifnameis a keyword or symbol with a namespace, the namespace will be included in the resulting value. Ifnameis a Var, the Var’s namespace will always be the namespace of the resulting value. Ifnameis a string with at least one ‘/’, the string will be split on the first ‘/’ character with the first segment being used asnsand the second asname.If
nsis notnil, then bothnameandnsmust be strings.
- fn (tagged-literal tag form)[source]¶
Construct a data representation of a tagged literal from a tag symbol and a form.
- fn (tagged-literal? o)[source]¶
Return true if the value is the data representation of a tagged literal.
- fn (take-nth n)[source]¶
- fn (take-nth n coll)
Return a lazy sequence of every
nth element ofcoll.Return a stateful transducer if no collection is provided.
- fn (take-while pred)[source]¶
- fn (take-while pred coll)
Return elements of
collwhile(pred elem)istrue.Return a transducer if no collection is provided.
- fn (tap> val)[source]¶
- fn (tap> topic val)
Send the value
valto 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
valwas sent to the queue,falseifvalwas dropped.
- fn (the-ns v)[source]¶
If
vis a symbol, return the Namespace named by that symbol if it exists. Ifvis a Namespace, return it. Otherwise, throw an exception.
- fn (thread-bound? & vars)[source]¶
Return
trueif vars are thread-bound, which implies that aset!will succeed. Returnstrueif no vars are given.
- macro (time expr)[source]¶
Time the execution of
expr. Return the result ofexprand 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
fwith starting arguments. Iffreturns 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
collby the transducing functionxf(created as(xform f)).If
collis empty, returninitwithout callingf. Ifinitis not given,fwill be called with no arguments to produce it.The transducing process will eagerly consume the input collection, calling
xfon 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 orxfreturns areducedvalue. 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 returntrueif a node might contain children (though it need not).childrenshould be a function of one argument which should return a sequence of children of a node.childrenwill only be called on a node ifbranch?returnstruefor 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. If one argument is
given, return 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-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. If one argument is
given, return 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-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 only one argument is 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
xto a float.Python does not differentiate between
floatanddouble. Pythonfloats 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
xto afloat.If
xis 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
xto anint.If
xis 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
xto 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. If one argument is given,
return 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-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. If one argument is given,
return 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-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
xto 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
tagandparentoriginally created viaderive.tagmay be either a valid Python type or a namespace-qualified keyword or symbol.parentmust be a namespace-qualified keyword or symbol.hmust be a hierarchy returned bymake-hierarchy. Ifhis 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
xis 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
kin associative data structuremwith the return value from calling(f old-v & args). Ifmisnil, use an empty map. Ifkis not inm,old-vwill benil.
- fn (update-in m ks f & args)[source]¶
Updates the value for key
kin associative data structuremwith the return value from calling(f old-v & args). Ifmisnil, use an empty map. Ifkis not inm,old-vwill benil.
- fn (update-keys m f)[source]¶
Update the keys in map
mby applying a function of one argument,f, to every key.fmust return a unique key for every input key, otherwise the behavior of this function is undefined.
- fn (update-proxy proxy mappings)[source]¶
Update the current proxy method map for the given proxy.
Method maps are maps of string method names to their implementations as Basilisp functions. If
nilis passed in place of a function for a method, that method will revert to its default behavior.Throws an exception if
proxyis not a proxy.
- fn (update-vals m f)[source]¶
Update the values in map
mby 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]
useis likerequirewhich also refers all Vars from the requiring Namespace afterwards. Libspecs passed tousemay include filters as defined inreferto 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
usedirectly is discouraged in favor of the:usedirective in thensmacro.
- fn (uuid-like? x)[source]¶
Return
trueifxis 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 (vals m)[source]¶
Return a seq of the values from a map-like object
If
misnil, returnnil.If
mis castable to a seq, cast it to a seq and callvalson that.If
mis a seq, yield the valuess from successive entries (which must be map entries).If
mis any type of mapping, return a seq of that mapping’s values.
- 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
vnon-atomically tonew-val. Returns the new value.
- fn (vswap! v f & args)[source]¶
Swap the value of volatile
vnon-atomically to the return of(apply f old-val args). Returns the new value of that function call.
- macro (when cond & body)[source]¶
Evaluate
condand if it is truthy, execute body in an implicitdoblock.
- 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. Returnnilotherwise.
- macro (when-let binding & body)[source]¶
Evaluate the binding as with
let, binding the given name for use in thetrueexpression iff the binding expression is truthy. Returnnilotherwise.
- macro (when-not cond & body)[source]¶
Evaluate
condand if it is falsey, execute body in an implicitdoblock.
- 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. Returnnilotherwise.
- macro (while cond & body)[source]¶
Execute
bodyrepeatedly (likely for side effects) untilcondreturnsfalse. Returnnil.
- macro (with bindings & body)[source]¶
Evaluate
bodywithin atry/exceptexpression, binding the named expressions as per Python’s context manager protocol spec (Python’swithblocks).
- macro (with-async bindings & body)[source]¶
Evaluate
bodywithin atry/exceptexpression, binding the named expressions as per Python’s async context manager protocol spec (Python’sasync withblocks).Warning
The
with-asyncmacro may only be used in an asynchronous function context.
- macro (with-bindings bindings-map & body)[source]¶
Execute the expressions given in the
bodywith the thread-local Var bindings specified in the Var/value mapbindings-mapinstalled.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
fwith the given argumentsargs(as byapply) with the thread-local Var bindings specified in the Var/value mapbindings-mapinstalled.The thread-local Var bindings will be popped after executing
fin all cases.Returns the return value of
f.
- macro (with-in-str s & body)[source]¶
Evaluate body with
*in*bound to aio.StringIOinstance containing the strings.
- fn (with-meta o meta)[source]¶
Return an object of the same type and representing the same value as
owithmetaas its metadata. Of Basilisp’s builtin types, only those implementing the interface IWithMeta supportwith-meta.
- macro (with-open & args)[source]¶
Evaluate
bodywithin atry/exceptexpression, binding the named expressions as per Python’s context manager protocol spec (Python’swithblocks).
- macro (with-out-str & body)[source]¶
Capture the contents of text sent to
*out*and return the contents as a string.
- macro (with-precision precision & exprs)[source]¶
Set the current precision and (optionally) rounding behavior of
decimal.Decimalinstances in the current thread while executingexprs.Rounding should be a symbol and may be one of: -
CEILING-FLOOR-UP-DOWN-HALF_UP-HALF_EVEN-HALF_DOWN-ZERO_FIVE_UP(corresponding with Python’sdecimal.ROUND_05UP)
- 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-indirectioncompiler flag at startup. Direct linking can be disabled for individual Vars by setting the^:redefmeta flag where the Var isdef‘ed.with-redefswill 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-indirectioncompiler flag at startup. Direct linking can be disabled for individual Vars by setting the^:redefmeta flag where the Var isdef‘ed.with-redefs-fnwill throw an Exception if directly linked Vars are given in the bindings.