basilisp.core

fn (*)
fn (* x)
fn (* x y)
fn (* x y & args)

Multiply the arguments. If no arguments given, returns 1.

dynamic Var *1

During a REPL session, bound to the most recent value evaluated.

dynamic Var *2

During a REPL session, bound to the second most recent value evaluated.

dynamic Var *3

During a REPL session, bound to the third most recent value evaluated.

dynamic Var *assert*
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} or nil otherwise.

Note that this value will differ from sys.argv since it will not include the command line arguments consumed by Basilisp’s own CLI.

dynamic Var *compiler-options*
dynamic Var *data-readers*

Data readers map which will be merged in to the default data reader map used by the reader. Mappings should be qualified symbols to functions taking one argument. The function will receive an unevaluated data structure and must return some value to the reader.

dynamic Var *default-reader-features*

The set of all currently supported reader features.

dynamic Var *e

During a REPL session, bound to the most recently thrown exception.

dynamic Var *err*

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 *executor-pool*
dynamic Var *flush-on-newline*

Indicates whether the :lpy:fn:prn and :lpy:fn:println functions should flush the output stream after the last newline is written.

Defaults to true.

dynamic Var *in*

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 *loaded-libs*
dynamic Var *main-ns*

The name of the main namespace as a symbol if this process was executed as basilisp run -n {namespace} or python -m {namespace} or nil otherwise.

This can be useful for detecting scripts similarly to how Python scripts use the idiom if __name__ == "__main__":.

dynamic Var *ns*

Pointer to the current namespace.

This value is used by both the compiler and runtime to determine where newly defined Vars should be bound, so users should not alter or bind this Var unless they know what they’re doing.

dynamic Var *out*

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 *pmap-cpu-count*
dynamic Var *print-dup*
dynamic Var *print-length*
dynamic Var *print-level*
dynamic Var *print-meta*
dynamic Var *print-namespace-maps*

Indicates to print the namespace of keys in a map belonging to the same namespace, at the beginning of the map instead of beside the keys. Defaults to false.

dynamic Var *print-readably*
dynamic Var *print-sep*
dynamic Var *python-version*

The current Python version as a vector of [major, minor, revision].

dynamic Var *resolver*

Resolver used for resolving namespace aliases when reading forms using read, read-string, etc.

fn (+)
fn (+ x)
fn (+ x y)
fn (+ x y & args)

Sum the arguments together. If no arguments given, returns 0.

fn (- x)
fn (- x y)
fn (- x y & args)

Subtract the arguments. If one argument given, returns the negation of that argument.

macro (-> x & forms)

Thread x through the forms. 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)

Thread x through the forms. Places x in the last position of the first form, and then the resulting expression into the last position of the second form, etc. Forms which are not lists will be made into lists.

type->Eduction
type->EductionSeq
fn (-collect-keyword-args kwargs)

Implementation detail for associative destructuring of function keyword arguments.

Collect all keyword arguments into a single map. Support trailing map arguments which are joined into the final map.

macro (.. x & method-calls)

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)
fn (/ x y)
fn (/ x y & args)

Divide the arguments. If no arguments given, returns the inverse of the argument.

fn (< _)
fn (< x & args)

Return true if arguments are monotonically increasing, otherwise false.

fn (<= _)
fn (<= x & args)

Return true if arguments are increasing, otherwise false.

fn (= _)
fn (= x & args)

Return true if x and y are equal, otherwise false.

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 (== & args)

Alias for lpy:fn:=.

fn (> _)
fn (> x & args)

Return true if arguments are monotonically decreasing, otherwise false.

fn (>= _)
fn (>= x & args)

Return true if arguments are decreasing, otherwise false.

typeEduction
typeEductionSeq
fn (NaN? x)

Return true if x is NaN.

fn (abs x)

Return the absolute value of x.

fn (aclone array)

Return a clone of the Python list.

fn (add-tap tf)
fn (add-tap topic tf)

Add tf, a function of one argument, to the tap set for the topic topic. 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)

Add a watch function wf identified by the key k to the ref (Atom or Var).

Watch functions should be functions of four arguments: the key associated with the watch function, the ref object, the old value, and the new value.

Watch functions will be called synchronously. Note that the value of a ref may have changed by the time a watch function is called, so watch functions should use the old and new state arguments rather than attempting to deref the ref.

Watch functions cannot prevent state changes to a ref, regardless of the result of the watch function.

Watch function keys are used to identify watches and may be used to remove a watch from a ref (using remove-watch), but are otherwise unused by the watch feature.

Watches for a Var are only notified for Var root changes, not thread-local bindings.

fn (aget array idx)
fn (aget array idx & idxs)

Return the value of the Python list at the index (or indices).

fn (alength array)

Return the length of the Python list.

fn (all-ns)

Return a sequence of all namespaces.

fn (alter-meta! o f & args)

Atomically swap the metadata on reference o to the result of (apply f m args) where m is the current metadata of o. f should be free of side effects. References include atoms, namespaces, and vars.

fn (alter-var-root v f & args)

Atomically alter the Var root by calling (apply f root args) and setting the root as the result.

macro (amap array idx ret expr)

Map expr over the Python list array, returning a new Python list with the result.

This macro initially binds the symbol named by ret to a clone of array. On each iteration, the index (named by idx) of ret is set to the return value of expr.

fn (ancestors tag)
fn (ancestors h tag)

Return the set of all ancestors (parents and grandparents and so forth) of tag in hierarchy h.

tag may be either a valid Python type or a namespace-qualified keyword or symbol. If tag is a Python type, ancestors include any relationships established via calls to derive as well as any superclasses (as returned by supers). If tag is a namespace-qualified keyword, only relationships from derive are returned.

h must be a hierarchy returned by make-hierarchy. If h is not supplied, the global hierarchy will be used.

macro (and)
macro (and & args)

Evaluate the expressions from left to right. If all expressions are truthy, return the result of the final expression. Otherwise, returns the first falsey expression. Calling and with no arguments returns true.

fn (any? _)

Return true for any x.

fn (apply f & args)

Apply function f to the arguments provided.

The last argument must always be coercible to a Seq. Intermediate arguments are not modified.

fn (apply-kw f & args)

Apply function f to the arguments provided, passing the keys from the final argument (which must be a map) as Python keyword arguments to f. 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)

Apply arguments to a method call. Equivalent to (apply (.-method o) args).

macro (areduce array idx ret init expr)

Reduce the Python list array by expr, returning the reduced expression.

This macro initially binds the symbol named by ret to init. On each iteration, ret is rebound to the return value of expr.

macro (as-> x name & forms)

Bind x to name and thread it through the forms, replacing instances of name in forms with the threaded expression.

fn (aset array idx val)
fn (aset array idx idx2 & idxs)

Sets the value of the Python list at the index (or indices). Returns val.

macro (assert expr)
macro (assert expr message)

Evaluate expr and if it returns logical false, throw an AssertionError.

This macro does not emit an assertion if the dynamic Var *assert* is set to a logical false value.

fn (assoc m k v)
fn (assoc m k v & kvs)

Associate keys to values in associative data structure m. If m is nil, returns a new map with key-values kvs.

fn (assoc! m k v)
fn (assoc! m k v & kvs)

Associate keys to values in the transient associative data structure m.

fn (assoc-in m ks v)

Associate value in a nested associative structure, with ks as a sequence of keys and v as the new value. If no map exists for any key in ks, a new empty map will be created.

fn (associative? x)

Return true if x implements IAssociative .

fn (atom v)
fn (atom v & kwargs)

Return an Atom containing v. The value of an Atom at any point in time may be returned by :lpy:fn`deref` ing it. The value of an atom may be reset using reset! and may be swapped using swap!. All operations on an atom occur atomically.

fn (bases cls)

Return the direct superclasses and interfaces of cls as a sequence.

fn (bigdec x)

Coerce x to a Python decimal.Decimal.

fn (bigint x)

Coerce x to an integer.

Python’s builtin int type is arbitrary precision, so there is no difference between bigint, biginteger, and Python’s builtin int.

fn (biginteger x)

Coerce x to an integer.

Python’s builtin int type is arbitrary precision, so there is no difference between bigint, biginteger, and Python’s builtin int.

macro (binding bindings & body)

Establish thread-local bindings for the vars given. The bindings are guaranteed to clear once execution passes outside the scope of this block.

fn (bit-and x & args)

Return the bitwise and of x and args.

fn (bit-and-not x & args)

Return the bitwise and complement of x and args.

fn (bit-clear x n)

Clear the bit of x at index n.

fn (bit-flip x n)

Flip the bit of x at index n.

fn (bit-not x)

Invert the bits of x.

fn (bit-or x & args)

Return the bitwise or of x and args.

fn (bit-set x n)

Set the bit of x at index n.

fn (bit-shift-left x n)

Return x shifted left n bits.

fn (bit-shift-right x n)

Return x shifted right n bits.

fn (bit-test x n)

Test the bit of x at index n.

fn (bit-xor x & args)

Return the bitwise xor of x and args.

fn (boolean x)

Coerce x to a boolean.

fn (boolean? o)

Return true if o is a boolean.

fn (booleans x)

Dummy cast to a Python list of booleans.

This function is provided for Clojure compatibility.

macro (bound-fn & fn-tail)

Return a function with the same function tail (everything after fn when defining a function) which will be executed with the same thread-local Var bindings as were in effect when bound-fn was called.

Returns the return value of the defined function.

This is primarily useful for creating functions which might need to run on a different thread, but which should have the same Var bindings in place as when it was defined.

fn (bound-fn* f)

Return a function which executes f with the same thread-local Var bindings as were in effect when bound-fn* was called.

f will be called with the same arguments as the returned function.

Returns the return value of f.

This is primarily useful for creating functions which might need to run on a different thread, but which should have the same Var bindings in place as when it was defined.

fn (bounded-count n coll)
fn (butlast coll)

Return all but the last element in a sequence in linear time.

fn (byte x)

Coerce x to a byte.

fn (byte-string x)
fn (byte-string x encoding)
fn (byte-string x encoding errors)

Coerce x to a byte string (Python bytes object).

Arguments shall be interpreted exactly as with that object’s constructor.

fn (byte-string? x)

Return true if x is a byte string (the Python bytes type).

Note that Python supplies byte string and byte array objects in its standard library. To check if an object is a Python bytearray, use bytes?.

fn (bytes x)

Dummy cast to a Python list of bytes (distinct from Python’s bytarray and bytes types).

This function is provided for Clojure compatibility.

fn (bytes? x)

Return true if x is a byte array (the Python bytearray type).

Note that Python supplies byte string and byte array objects in its standard library. This function complies with Clojure’s standard library in returning true iff x is a Python bytearray. To check if an object is a Python bytes, use byte-string? .

macro (case expr & clauses)

Switch on expr to return a matching clause from the set of input clauses.

The input expression may be any valid Basilisp expression. A single default expression can follow the clauses, and its value will be returned if no clause matches.

The clauses are pairs of a matching value and a return value. The matching values are not evaluated and must be compile-time constants. Symbols will not be resolved. Lists may be passed to match multiple compile time values to a single return value. The dispatch is done in constant time.

fn (cast cls x)

Throws a TypeError if x is not a cls. Otherwise, return x.

fn (cat rf)

A transducer which concatenates input collections into the reduced result.

fn (char x)

Coerce x to a string of length 1.

Natural integers are treated as ordinals and passed to Python’s chr. Strings of length 1 are returned as such. Other types will result in a ValueError.

fn (char? x)

Return true if x is a string of length 1.

fn (chars x)

Dummy cast to a Python list of chars.

This function is provided for Clojure compatibility.

fn (class x)

Return the class of x.

fn (class? x)

Return true if x names a type.

fn (coll? x)

Return true if x implements IPersistentCollection.

macro (comment & forms)

Ignore all the forms passed, returning nil.

fn (comp)
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)

Return either -1, 0, or 1 to indicate the relationship between x and y.

This is a 3-way comparator commonly used in Java-derived systems. Python does not typically use 3-way comparators, so this function convert’s Python’s __lt__ and __gt__ method returns into one of the 3-way comparator return values.

Comparisons are generally only valid between homogeneous objects, with the exception of numbers which can be compared regardless of type. Most scalar value types (including nil, booleans, numbers, strings, keywords, and symbols) are comparable. nil compares less than all values except itself. NaN compares equal to all numbers, including itself. Strings are compared lexicographically. Symbols and keywords are sorted first on their namespace, if they have one, and then on their name. Symbols and keywords with namespaces always sort ahead of those without. Symbols cannot be compared to keywords.

Of the built in collection types, only vectors can be compared. Vectors are compared first by their length and then element-wise.

Other collections such as maps, sequences, and sets cannot be compared.

Python objects supporting __lt__ and __gt__ can generally be compared.

fn (compare-and-set! atom old-val new-val)

Atomically set the value of atom to new-val if and only if old-val is the current value of the atom.

fn (complement f)

Return a function which returns the logical complement of the return value of (apply f args).

fn (completing f)
fn (completing f cf)

Given a reducing function of two arguments, f, return a function with both 0-, 1-, and 2-arities appropriate for transduce. The 0-arity will return a call to f with no arguments. The 1-arity will call cf on its argument. The 2-arity will call f directly with both of its arguments.

If cf is not given, identity will be used.

fn (complex? x)

Return true if x is a complex number.

fn (concat & seqs)

Concatenate the sequences given by seqs into a single Seq.

macro (cond & clauses)

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)

Takes a test and form pair, threading x (as by ->) through each form for which the corresponding test evaluates as true. cond-> does not short circuit evaluation in any case.

macro (cond->> x & clauses)

Takes a test and form pair, threading x (as by ->>) through each form for which the corresponding test evaluates as true. cond->> does not short circuit evaluation in any case.

macro (condp pred expr & clauses)

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 the condp expression.

Clauses can take two forms:

  • test-expr result-expr

  • test-expr :>> result-fn where :>> is a keyword literal

For the ternary expression clause, the unary result-fn will be called with the result of the predicate.

fn (conj coll x)
fn (conj coll x & xs)

Conjoin xs to collection coll. New elements may be added in different positions depending on the type of coll. conj returns the same type as coll. If coll is nil, return a list with xs conjoined.

fn (conj!)
fn (conj! coll)
fn (conj! coll & xs)

Conjoin xs to the transient collection `coll. New elements may be added in different positions depending on the type of coll. conj! returns the same type as coll.

fn (cons o seq)

Creates a new sequence where o is the first element and seq is the rest. If seq is nil, return a list containing o. If seq is not a Seq, attempt to coerce it to a Seq and then cons o onto the resulting sequence.

fn (constantly x)

Returns a function that accepts any number of arguments and returns x.

fn (contains? coll k)

Return true if coll contains k. For vectors, k is an index. For maps, k is a key. For sets, k is a value in the set.

fn (count coll)

Return the length of coll as by Python’s len builtin, or 0 if coll is nil. If the collection does not respond to __len__, then count it manually.

fn (counted? x)

Return true if x can be counted in constant time.

fn (create-ns ns-sym)

Create a Namespace with the name ns-sym or return the existing one if it already exists.

fn (cycle coll)

Cycle the items in coll infinitely.

fn (dec x)

Decrement the argument by 1.

fn (decimal? x)

Return true if x is a Decimal.

macro (declare & names)

Declare the given names as Vars with no bindings, as a forward declaration.

fn (dedupe)
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)

Define a new asynchronous function as by defn.

Asynchronous functions are compiled as Python async def s.

Var default-data-readers

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)

Define a new Python interface (abstract base clase) with the given name and method signatures.

Method signatures are in the form (method-name [arg1 arg2 ...]). self or this arguments must be omitted from all interfaces.

Interface objects cannot be directly instantiated. Instead, you must create a concrete implementation of an interface (perhaps via deftype) and supply implementations for all of the abstract methods.

The generated interface derives from Python’s abc.ABC and all method definitions are declared as abc.abstractmethod s and thus must be implemented by a concrete type.

Interfaces created by definterface cannot be declared as properties, class methods, or static methods, as with deftype.

macro (defmacro body)
macro (defmacro & body)
macro (defmacro attr-map? & body)

Define a new macro function. The arguments and syntax of defmacro are identical to that of defn.

When the compiler encounters a new macro function invocation, it immediately invokes that function during compilation and substitutes the function invocation with the return value of the called macro. Macros must return valid syntax at the point they are invoked, otherwise the compiler will throw an exception and compilation will halt.

Macros created by defmacro have access to two implicit arguments whose names must not appear in your argument list:

  • &env is a map of all symbol bindings available to the compiler at the point the macro is invoked.

  • &form is the original form invoking the macro. This is often useful for reading and copying metadata attached to the original form.

macro (defmethod multifn dispatch-val & fn-tail)

Add a new method to the multimethod multifn which responds to dispatch-val.

fn-tail is the trailing part of a function definition after fn including any relevant argument vectors.

Methods added to a multimethod can be removed using remove-method. All methods may be removed using remove-all-methods.

See defmulti for more information about multimethods.

macro (defmulti name & body)

Define a new multimethod with the given name and a body consisting of an optional docstring, optional metadata map, a dispatch function and options of key/value pairs.

Multimethod dispatch functions should be defined with the same arity or arities as the registered methods. The provided dispatch function will be called first on all calls to the multimethod and should return a dispatch value which will be used to identify a registered method. If the value returned by the dispatch function does not correspond to a registered method, the method registered with the default dispatch value, if one is registered, will be called instead. Methods can be registered with the defmethod macro.

Multimethods select a dispatch method by using isa? on all available dispatch values. Callers can provide a hierarchy to use for isa? resolution. For cases where multiple dispatch values are registered which may return true for a call to isa? callers must select preferred values using prefer-method or a RuntimeException will be thrown when a unique method cannot be selected. Callers can view multimethod preferences by calling prefers.

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 a Var)

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.

macro (defn body)
macro (defn & body)
macro (defn attr-map? & body)

Define a new function with an optional docstring.

The function will be interned in the current Namespace as a Var using the given name.

After the name, an optional mapping of meta attributes may be provided. Any metadata values given will be attached to the metadata of the interned Var. A few special meta keys change how defn emits the final Var and function:

  • :decorators is an optional vector of functions which will wrap the final function emitted by defn. Like standard Python decorators and the comp function, decorators are applied to the generated function from right to left.

Specify an optional docstring after the metadata map to provide callers with additional details about your function, its arguments, and its return value. If a docstring is provided, it will be attached to the interned Var metadata under the :doc key.

Functions may be defined with 1 or more arities. Functions of a single arity may be defined with a single vector of 0 or more arguments after the optional metadata map. Any forms appearing after the argument vector will be part of the function body. It is legal to define a function with no body. In this case, your function will always return nil.

Functions with multiple arities are defined as a series of lists after the optional metadata map. Each list must contain an argument vector and 0 or more body forms. No arity may share the same number of fixed (non-variadic) arguments. There may be at most one variadic arity defined per function and the number of fixed arguments to that arity must be greater than or equal than the number of fixed arguments of all other arities.

macro (defn- name & body)

Define a new private function as by defn.

Private functions are def ‘ed with the :private metadata, which makes them ineligible for access outside the namespace using require or refer.

macro (defonce name expr)

Define the Var named by name with root binding set to expr if and only if a name is not already defined as a Var in this namespace. expr will not be evaluated if the Var already exists.

macro (defprotocol protocol-name & methods)

Define a new protocol.

Protocols are similar to classical programming interfaces. Rather than defining an interface and implementing that interface on different objects, protocols generate a set of functions which dispatch to the correct implementation on the type of their first argument (which is similar to the Python self argument).

Also like interfaces, Protocols do not include implementations for any of their member methods. Instead, implementations can be provided using deftype, defrecord, reify, or extend (or any of the extend-* macros).

Despite their differences from interfaces, Protocols do also generate a standard Python interface type (deriving from abc.ABC) which is used for efficient dispatch for implementing types.

Method signatures are in the form:

(method-name [self arg1] [self arg1 arg2] "This method foos the bars.")

Callers must provide the self or this arguments for each method.

macro (defrecord type-name fields & method-impls)

Define a new Basilisp record.

The new record will have fields matching the names in fields. Fields may be referred to unqualified in the bodies of implemented methods.

Interface or protocol implementations are declared as the name of the interface or protocol as a symbol, followed by 1 or more method definitions for that interface. Types are not required to declare any interface implementations. Types which do declare interface implementations are required to implement all interface methods. Failing to implement all interface methods is a compile time error. Types implementing object are not required to implement all object methods.

Method declarations should appear as:

(method-name [arg1] & body)
(method-name [arg1 arg2 ...] & body)

Records objects are created with sensible object defaults as by attrs. New records may override object defaults. An __init__ function is automatically created which takes positional arguments matching the order of definition in fields. Additionally, given a name NewRecord, a factory function will be created ->NewRecord which can be used to generate new instances of the record.

Methods must supply a this or self parameter. recur special forms used in the body of a method should not include that parameter, as it will be supplied automatically.

macro (deftype type-name fields & method-impls)

Define a new Python concrete type which can implement 0 or more Python interfaces or Basilisp protocols.

The new type will have fields matching the names in fields. Fields may be referred to unqualified in the bodies of implemented methods. By default the fields of this type are immutable. Attempting to set non-mutable fields from a method body will result in a compiler error.

Fields may be made mutable by annotating their definition with :mutable metadata. Mutable fields may be set within method bodies using the set! 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 using set!, so bear that in mind when choosing mutability.

Interface or protocol implementations are declared as the name of the interface or protocol as a symbol, followed by 1 or more method definitions for that interface. Types are not required to declare any interface implementations. Types which do declare interface implementations are required to implement all interface methods. Failing to implement all interface methods is a compile time error. Types implementing object are not required to implement all object methods.

Method declarations should appear as:

(method-name [arg1] & body)
(method-name [arg1 arg2 ...] & body)

Unlike in Clojure, interface and protocol methods are permitted to include variadic arguments. Single-arity methods may also declare support for keyword arguments using either the :apply or :collect strategy on the :kwargs metadata on the method name. Methods may be declared as static (using the :staticmethod meta key) or class methods (using the :classmethod meta key). Both static methods and class methods can be declared with multiple arities or may be defined with a single arity and keyword arguments. Finally, single-arity methods may be declared as Python properties using the :property metadata on the method name. These facilities are provided as a means to interoperate with Python code and their use is discouraged in pure Basilisp code.

Type objects are created with sensible object defaults as by attrs. New types may override object defaults. An __init__ function is automatically created which takes positional arguments matching the order of definition in fields. Additionally, given a name NewType, a factory function will be created ->NewType which can be used to generate new instances of the type.

Methods must supply a this or self parameter. recur special forms used in the body of a method should not include that parameter, as it will be supplied automatically.

macro (delay & body)

Takes a body of expressions producing any value. Will not produce a value until deref ed. The result is cached and returned in future derefs.

fn (delay? x)

Return true if x names a delay.

fn (deliver p v)

Deliver the value v to the promise p. If p already has a value, then a subsequent call to deliver for p will have no effect.

fn (denominator frac)

Return the denominator of a Fraction.

fn (deref o)
fn (deref o timeout-s timeout-val)

Dereference a delay or atom and returns its contents.

If o is an object implementing IBlockingDeref and timeout-s and timeout-val are supplied, deref will wait at most timeout-s seconds, returning timeout-val if timeout-s seconds elapse and o has not returned.

fn (derive tag parent)
fn (derive h tag parent)

Derive a parent/child relationship between tag and parent.

tag may be either a valid Python type or a namespace-qualified keyword or symbol.

parent must be a namespace-qualified keyword or symbol.

h must be a hierarchy returned by make-hierarchy . If h is not supplied, the global hierarchy will be used.

Relationships may be removed via underive.

fn (descendants tag)
fn (descendants h tag)

Return the set of all descendants (children and grandchildren and so forth) of tag in hierarchy h.

tag must be a namespace-qualified keyword or symbol. Python types are not supported for descendants checks.

h must be a hierarchy returned by make-hierarchy. If h is not supplied, the global hierarchy will be used.

fn (destructure [binding expr])

Take a [binding expr] pair (as from a let block) and produce all of the replacement bindings for the binding which perform destructuring on the initial expression.

As an example, for sequential destructuring like:

[f & r :as v] [1 2 3 4]

This function would emit a list of bindings which can be inserted directly into a let* binding to perform destructuring:

(v [1 2 3 4]
 f (nth v 0)
 r (nthnext v 1))
fn (disj s)
fn (disj s elem)
fn (disj s elem & elems)

Return a new version of the set s without the given elements. If the elements don’t exist in s, they are ignored.

fn (disj! s)
fn (disj! s elem)
fn (disj! s elem & elems)

Return a new version of the transient set s without the given elements. If the elements don’t exist in s, they are ignored.

fn (dissoc m)
fn (dissoc m k)
fn (dissoc m k & ks)

Return a new version of m without the given keys. If the keys don’t exist in m, they are ignored.

fn (dissoc! m k)
fn (dissoc! m k & ks)

Return a new version of the transient associative collection m without the given keys. If the keys don’t exist in m, they are ignored.

fn (distinct)
fn (distinct coll)

Return a lazy sequence of the elements of coll, removing duplicates.

Return a stateful transducer if no collection is provided.

fn (distinct? & args)

Return true if no two arguments are equal.

fn (doall coll)
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)
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)

Repeatedly run the body (likely for side effects) with bindings as described in the for macro. Returns nil.

macro (dotimes binding & body)

Repeatedly execute body (likely for side effects) while the binding name is repeatedly rebound from 0 to the binding value, n, minus 1. Returns nil.

macro (doto x & forms)

Evaluate x and thread it as the first argument in all of the given forms. Returns x.

Useful for creating a Python class and calling methods on it for initialization before returning the class.

fn (double x)

Coerce x to a float.

Python does not differentiate between float and double. Python float s are double precision.

fn (double? & args)

Return true if o is a float.

Same as float?. Python does not distinguish between single and double precision floating point numbers, so all floating points are called float and are double precision.

fn (doubles x)

Dummy cast to a Python list of doubles.

This function is provided for Clojure compatibility.

fn (drop n)
fn (drop n coll)

Drop the first n elements of coll.

Return a stateful transducer if no collection is provided.

fn (drop-last coll)
fn (drop-last n coll)

Drop all but the last n items of coll.

fn (drop-while pred)
fn (drop-while pred coll)

Drop elements of coll until (pred elem) returns true.

Return a stateful transducer if no collection is provided.

fn (eduction & args)

Return an iterable which is the application of the transducers xform* to the input collection coll. Transducers will be applied to comp in the given order.

Unlike with sequence, eduction returns an iterable type which does not cache its results. As such, any computation will be performed again on each iteration.

Eductions are likely to be more efficient in contexts where you would plan to consume the entire input collection and only plan to use that computation once. For cases with an infinite input sequence or if you need caching, sequence is preferred.

fn (empty coll)

Return an empty collection of the same interface type as coll, or nil.

fn (empty? coll)

Return true if coll is empty (as by (not (seq coll))).

Typically, you should prefer the idiom (seq coll) to (not (empty? coll)).

fn (ensure-reduced x)

If x is not a reduced value, wrap it (as by reduced) and return the wrapper. Otherwise return x.

fn (eval form)
fn (eval form namespace)

Evaluate a form (not a string) and return its result.

If namespace is given, evaluate code in that Namespace. Otherwise, the current value of *ns* is used.

fn (even? x)

Return true if x is even.

fn (every-pred pred)
fn (every-pred pred & preds)

Return a predicate composed of all of the input predicates, which returns true if all input predicates return true for a value, otherwise returns false. The returned predicate returns false on the first failing predicate and will not execute any remaining predicates.

fn (every? pred coll)

Return true if every element in coll satisfies pred.

multi fn (evolve & args)

Implementation detail of defrecord.

fn (ex-cause ex)

Return the cause (another Exception) of ex if it derives from Exception, otherwise it returns nil.

fn (ex-data ex)

Return the data map of ex if is an instance of IExceptionInfo, otherwise it returns nil.

fn (ex-info msg data)

Returns a basilisp.lang.exception/ExceptionInfo instance with the given message and data.

fn (ex-message ex)

Return the message of ex if is an Exception, otherwise it returns nil.

fn (extend target-type & proto+methods)

Extend a type dynamically with one or Protocol implementations. This is useful for types which were defined outside your control or which were not otherwise defined as direct implementors of the named Protocol(s). With extend, such types may be extended without modifying the types directly.

target-type should name a type which is to be extended. Virtually any type is permitted, so long as that that type is not also a Protocol. If target-type is an interface, objects of types implementing that interface will be extended by the given implementation unless a more concrete implementation is available (by the Python method resolution order of the object’s type). If target-type` is ``nil, it will be interpreted as (python/type nil).

proto+methods are interleaved Protocol names and maps of Protocol method implementations intended for target-type. The keys of each map are keywords corresponding to the names of the Protocol methods (as defined in the defprotocol). Each value should be either an existing function (referenced by its Var or name binding) or a new function definition.

extend may be called multiple times for a single target-type, so not all implementations need to be known a priori. Successive calls to extend on target-type with the same Protocol implementations will overwrite previous implementations.

If you are extending types with explicit function definitions, the extend-protocol and extend-type macros offer some additional conveniences.

Returns nil.

Example:

(extend SomeType
  FirstProto
  {:spam spam-fn
   :eggs (fn [...] ...)}
  OtherProto
  {:ham  (fn [...] ...)})
macro (extend-protocol proto & specs)

Extend a Protocol with implementations for multiple types.

This convenience macro is useful for extending multiple different types with a single Protocol definition in one call. Note that this macro only supports new function declarations. If you intend to reference an existing function, call extend directly.

For example, this call:

(extend-protocol SomeProto
  FirstType
  (spam
    ([this] ...)
    ([this arg] ...))
  (eggs [this arg1 arg2] ...)
  OtherType
  (spam
    ([this] ...)
    ([this arg] ...))
  (eggs [this arg1 arg2] ...))

Would be turned into the following extend calls:

(do
  (extend FirstType
    SomeProto
    {:spam (fn spam
             ([this] ...)
             ([this arg] ...))
     :eggs (fn [this arg1 arg2] ...)})
  (extend OtherType
    SomeProto
    {:spam (fn spam
             ([this] ...)
             ([this arg] ...))
     :eggs (fn [this arg1 arg2] ...)}))
macro (extend-type target-type & specs)

Extend a type with multiple Protocol implementations.

This convenience macro is useful for extending a single type with multiple different Protocol definitions in one call. Note that this macro only supports new function declarations. If you intend to reference an existing function, call extend directly.

For example, this call:

(extend-type SomeType
  FirstProto
  (spam
    ([this] ...)
    ([this arg] ...))
  (eggs [this arg1 arg2] ...)
  SecondProto
  (ham [this & args] ...))

Would be turned into the following extend call:

(extend SomeType
  FirstProto
  {:spam (fn spam
           ([this] ...)
           ([this arg] ...))
   :eggs (fn eggs [this arg1 arg2] ...)}
  SecondProto
  {:ham (fn ham [this & args] ...)})
fn (extenders {:as proto :keys [impls]})

Return a collection of types explicitly extending protocol proto.

The returned collection will not include types which extend proto via inheritance (as by deftype and :lpy:fn`defrecord`). Only types extending proto via extend (or extend-protocol or extend-type) will appear.

fn (extends? {:as proto :keys [interface impls]} type)

Return true if type extends protocol proto.

fn (false? x)

Return true if x is false, otherwise false.

fn (ffirst seq)

Returns the first element in the first element of a Seq.

fn (file-seq dir)

Return a seq of pathlib.Path objects for all files and subdirectories of dir.

fn (filter pred)
fn (filter pred coll)

Return a lazy sequence of elements from coll where (pred elem) returns a truthy value.

Return a transducer if no collection is provided.

fn (filterv & args)

Return a vector of elements from coll where (pred elem) returns a truthy value.

fn (find m k)

Find the map entry of k in m, if it exists. Return nil otherwise.

fn (find-ns sym)

Return the namespace named by sym if it exists, or nil otherwise.

fn (find-var sym)

Return the Var named by namespace-qualified sym if it exists, or nil otherwise.

fn (first seq)

If seq is a Seq, return the first element from seq. If seq is nil, return nil. Otherwise, coerces seq to a Seq and returns the first element.

fn (flatten v)

Flatten any combination of nested sequences (such as lists or vectors) into a single lazy sequence. Calling flatten on non-sequential values returns an empty sequence.

fn (float x)

Coerce x to a float.

If x is string, it is parsed as a floating point number.

fn (float? o)

Return true if o is a float.

fn (floats x)

Dummy cast to a Python list of floats.

This function is provided for Clojure compatibility.

fn (flush)

Flush the buffer currently bound to *out*.

macro (fn & body)

Return an anonymous (but possibly named) function.

Function argument vectors support sequential and associative Destructuring .

See fn for more details.

fn (fn? x)

Return true if x is a function created by fn or fn*.

fn (fnext v)

Return the result of calling (first (next v)).

macro (for bindings & body)

Produce a list comprehension from 1 or more input sequences, subject to optional modifiers.

For comprehensions consist of a vector of bindings, with optional modifiers, and a user specified body in an implicit do block.

Symbol bindings look like standard let bindings. Values bound to symbols should be sequences or otherwise seqable. The body of the for comprehension will be executed with the given symbol bound to successive values of the sequence. If multiple sequences are bound to symbols, iteration will proceed in a nested fashion with latest sequences iterated first and earlier sequences iterated later (as nested for loops in procedural languages).

For example, a simple non-nested for comprehension will yield:

(for [x [1 2 3 4]] x) ;;=> [1 2 3 4]

However, a nested comprehension will yield a longer sequence:

(for [x (range 3)
      y [:a :b :c]]
  [x y])
;;=> ([0 :a] [0 :b] [0 :c]
      [1 :a] [1 :b] [1 :c]
      [2 :a] [2 :b] [2 :c])

Each set of symbol bindings may be modified by applying trailing bindings denoted with keywords. The keyword modifiers are:

keyword :let [sym val]:

:let bindings work like any standard let bindings; destructuring is permitted; may refer to any previous bindings in other :let modifiers or normal symbol bindings. Multiple pairs of bindings may appear in :let bindings.

keyword :when expr:

:when bindings are applied to the sequence roughly like in the core filter function; the expression is evaluated and if it is not falsey, yield the next value. As with :let bindings, the expression may refer to any previously bound names.

keyword :while expr:

:while bindings terminate the current sequence at the first point when expr returns a falsey value. :while bindings may refer to any previous bound names.

Multiple keyword modifiers may be applied to the previous binding. Their effects will be applied at the point they appear in the bindings vector.

fn (force x)

If x is a Delay, returned the possibly cached value of x. Otherwise, return x.

fn (format fmt & args)

Format a string as by Python’s % operator.

fn (frequencies coll)

Return a map whose keys are the elements of coll and whose values are the counts for the number of times the key appears in coll.

macro (future & body)

Execute the expressions of body in another thread. Returns a Future object. The value returned by the body can be fetched using deref or @, though doing so may block unless the deref with a timeout argument is used.

fn (future-call f)
fn (future-call f pool)

Call the no args function f in another thread. Returns a Future object. The value returned by f can be fetched using deref or @, though doing so may block unless the deref with a timeout argument is used.

fn (future-cancel fut)

Attempt to cancel the Future fut. If the future can be cancelled, return true. Otherwise, return false.

fn (future-cancelled? fut)

Return true if the Future fut has been cancelled, false otherwise.

fn (future-done? fut)

Return true if the Future fut is done, false otherwise.

fn (future? x)

Return true if x is a future, false otherwise.

fn (gen-interface & opts)

Generate and return a new Python interface (abstract base clase).

Options may be specified as key-value pairs. The following options are supported:

keyword :name:

the name of the interface as a string; required

keyword :extends:

a vector of interfaces the new interface should extend; optional

keyword :methods:

an optional vector of method signatures without self or this, like:

[ (method-name [args ...] docstring) ... ]

Callers should use definterface to generate new interfaces.

fn (gensym)
fn (gensym prefix)

Generate a unique symbol name of the form prefix_#. If no prefix is given, then v_ will be used.

fn (get m k)
fn (get m k default)

Return the entry of m corresponding to k if it exists or nil or default (if specified) otherwise.

m may be any associative type (such as a vector or map), set type, or string. If m is not one of the supported types, get always returns nil or default (if specified).

fn (get-in m ks)
fn (get-in m ks default)

Return the entry of an associative data structure addressed by the sequence of keys ks or default (default: nil) if the value is not found.

fn (get-method multifn dispatch-val)

Return the method of multimethod multifn which would respond to dispatch-val or nil if no method exists for dispatch-val.

fn (get-thread-bindings)

Return the current thread-local bindings as a map of Var/value pairs.

fn (get-validator ref)

Return the validator defined for the ref (Atom or Var), or nil if no validator is defined.

fn (group-by f coll)

Return a map whose keys are the result of calling f on each element in coll and whose values are vectors of the values which produced the corresponding key, in the order they were added.

fn (halt-when pred)
fn (halt-when pred retf)

Return a transducer which ends the tranducing process the first time pred returns a truthy value for an input.

If retf is given, it will be passed two arguments if a halt occurs. The first argument is the current result and the second is the input which triggered the halt. The return value of calling retf will be the return value of the transducer.

If retf is not given, the default retf will return the value which triggered the halt.

fn (hash x)

Return the hash code for its argument.

fn (hash-map & kvs)

Create a hash map from pairs of input arguments.

fn (hash-set & members)

Create a set from the input arguments.

fn (ident? x)

Return true if x is either a keyword or symbol.

fn (identical? x y)

Return true if x and y are the same object, otherwise false.

fn (identity v)

Returns its argument unmodified.

macro (if-let binding true-cond false-cond)

Evaluate the binding as with let, binding the given name for use in the true expression iff the binding expression is truthy . Otherwise, return the false expression without binding the name.

macro (if-not cond true-cond false-cond)

Evaluate cond and if it is true, return false-cond. Otherwise return true-cond.

macro (if-some binding true-cond false-cond)

Evaluate the binding as with let, binding the given name for use in the true expression iff the binding expression is not nil. Otherwise, return the false expression without binding the name.

fn (ifn? x)

Return true if x is callable as a function.

Many Basilisp data structures are callable as functions though they are not proper function types.

macro (import & modules)

Import Python modules by name.

Modules may be specified either as symbols naming the full module path or as a vector taking the form [full.module.path :as alias].

Note that unlike in Python, import ed Python module names are always hoisted to the current Namespace, so imported names will be available within a Namespace even if the import itself occurs within a function or method.

Use of import directly is discouraged in favor of the :import directive in the ns macro.

fn (in-ns & args)
fn (inc x)

Increment the argument by 1.

fn (indexed? x)

Return true if elements of x can be accessed by index efficiently.

fn (infinite? x)

Return true if x is either positive or negative infinity.

fn (instance? class obj)

Return true if obj is an instance of class.

fn (int x)

Coerce x to an integer.

If x is string, it is parsed as a base 10 number.

fn (int? & args)

Return true if x is an integer.

Note that unlike Clojure, Basilisp uses Python integers and there is no distinction between standard and fixed-precision integers.

fn (integer? o)

Return true if o is an integer.

fn (interleave)
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)
fn (intern ns name val)

Finds or creates a Var in ns (which may be either a namespace or symbol), setting the root binding to val, if provided. The namespace must exist. Return the Var.

fn (interpose sep)
fn (interpose sep coll)

Return a lazy sequence of elements of coll separated by sep. If coll is empty, return an empty sequence.

Return a stateful transducer if no collection is provided.

fn (into)
fn (into to)
fn (into to from)
fn (into to xform from)

Return a new collection created by adding all of the elements of from to the existing to collection to, as by conj.

A transducer may be provided as xform to transform the elements as they are copied.

into will attempt to use transient collections whenever possible to improve performance.

fn (into-array aseq)
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)

Dummy cast to a Python list of integers.

This function is provided for Clojure compatibility.

fn (isa? tag parent)
fn (isa? h tag parent)

Return true if tag is equal to parent or is a descendant of parent in hierarchy h.

Both tag and parent may be a valid Python type or a namespace-qualified keyword or symbol or a vector of namespace-qualified keywords or symbols. If either of tag or parent is a vector, the other must be a vector as well.

Ancestors will be fetched for tag using ancestors.

h must be a hierarchy returned by make-hierarchy. If h is not supplied, the global hierarchy will be used.

fn (iterate f x)

Returns a lazy sequence of x, (f x), (f (f x)) and so on.

fn (iteration step & {:keys [somef vf kf initk] :or {kf identity somef some? initk nil vf identity}})

Return a reducible sequence via repeated calls to step, a function of a “continuation token”, k.

step will initially be called with initk. 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 neither kf nor vf will be called. If the iteration continues, step will be called again with the result of (kf ret).

Only step is a required argument. somef defaults to some?, vf and kf default to identity, and initk defaults to nil.

For the purposes of this function, step should be considered an impure function and repeated calls to it even with the same token may not necesarily return the same values.

fn (juxt & args)

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)
fn (keep f coll)

Return a lazy sequence of non- nil results of (f elem) for elements in coll.

Return a transducer if no collection is provided.

fn (keep-indexed f)
fn (keep-indexed f coll)

Return a lazy-sequence of non- nil results of (f index elem) for elements in coll.

Return a stateful transducer if no collection is provided.

fn (key entry)

Return the key from a map entry.

fn (keys m)

Return a seq of the keys from a map.

fn (keyword name)
fn (keyword ns name)

Create a new keyword with name and optional namespace ns. Keywords will have the colon prefix added automatically, so it should not be provided.

fn (keyword? o)

Return true if o is a keyword.

fn (last s)

Return the last item in a seq, or nil if the seq is empty.

macro (lazy-cat & colls)

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)

Takes a body of expressions which will produce a seq or nil. When seq is first called on the resulting lazy-seq, the sequence will be realized.

macro (let bindings & body)

let bindings with Destructuring support.

macro (letfn bindings & body)

Let form specifically for local function definitions.

Functions are defined as bindings:

(letfn [(plus-two [x] (+ (plus-one x) 1))
        (plus-one [x] (+ x 1))]
  (plus-two 3))

Functions defined in letfn bindings may refer to each other regardless of their order of definition.

See letfn for more details.

fn (lisp->py o)
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-fn is the function name.

fn (list & args)

Create a list from the arguments.

fn (list? o)

Return true if o is a list.

fn (load & paths)

Read and evaluate the set of forms contained in the files identified by paths.

The provided paths should not include a file suffix.

Most often this is useful if you want to split your namespace across multiple source files. require will try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario). load will load the contents of the named file directly into the current namespace.

A path is interpreted relative to the syspath if it starts with a forward slash or relative to the root directory of the current namespace otherwise.

Note that unlike require, files loaded by load will not be cached and will thus incur compilation time on subsequent loads.

This function is provided for compatibility with Clojure. Users should prefer load-file (or perhaps load-reader or load-string) to this function.

fn (load-file path)

Read and evaluate the set of forms contained in the file located at path.

Most often this is useful if you want to split your namespace across multiple source files. require will try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario). load-file will load the contents of the named file directly into the current namespace.

Note that unlike require, files loaded by load-file will not be cached and will thus incur compilation time on subsequent loads.

fn (load-reader reader)

Read and evaluate the set of forms in the io.TextIOBase instance reader.

Most often this is useful if you want to split your namespace across multiple source files. require will try to force you into a namespace-per-file paradigm (which is generally preferred, but not right in every scenario). load-reader will load the contents of the named file directly into the current namespace.

Note that unlike require, files loaded by load-reader will not be cached and will thus incur compilation time on subsequent loads.

fn (load-string s)

Read and evaluate the set of forms contained in the string s.

fn (loaded-libs)

Return a set of all loaded Basilisp namespace names as symbols.

Namespace names are only added to this list if they appear in an ns macro.

fn (long x)

Coerce x to an integer.

Python does not support long types, so the value is coerced to an integer.

fn (longs x)

Dummy cast to a Python list of longs.

This function is provided for Clojure compatibility.

macro (loop bindings & body)

loop bindings with Destructuring support.

fn (macroexpand form)

Repeatedly macroexpand form as by macroexpand-1 until form no longer represents a macro. Returns the expanded form. Does not macroexpand child forms.

fn (macroexpand-1 form)

Macroexpand form one time. Returns the macroexpanded form. The return value may still represent a macro. Does not macroexpand child forms.

fn (make-array size)
fn (make-array type size)
fn (make-array type size & more-sizes)

Create a Python list with initial size. If multiple sizes are provided, produces a multi-dimensional list-of-lists. There is no efficient way to allocate such multi-dimensional lists in Python, so this function will run in polynomial time.

Python lists do not support pre-allocation by capacity, so this function pre-fills the created list(s) with nil.

The type argument is ignored and is provided only for Clojure compatibility.

fn (make-hierarchy)

Return a hierarchy that may be used to establish parent and child relationships via derive (relationships may be removed via underive).

Relationships can be queried using ancestors, descendants, parents, and isa?.

fn (map f)
fn (map f coll)
fn (map f coll & colls)

Return a lazy sequence of (f elem) for elements in coll. More than one collection may be supplied. If more than one collection is supplied, the function f will be passed sequential elements from each collection on each invocation and must be able to accept as many arguments as there are collections. The sequence will terminate when at least one input collection is exhausted.

Return a transducer if no collection is provided.

fn (map-entry coll)
fn (map-entry k v)

With one argument, coerce the input to a map entry. With two arguments, return a map entry containing key and value.

fn (map-entry? x)

Return true if x implements IMapEntry.

fn (map-indexed f)
fn (map-indexed f coll)

Return a lazy sequence of (f idx elem) for elements in coll. The index starts at 0.

Return a stateful transducer if no collection is provided.

fn (map? o)

Return true if o is a map.

fn (mapcat f)
fn (mapcat f coll)
fn (mapcat f coll & colls)

Return a lazy sequence of the concatenated results of mapping f over colls.

fn (mapv & args)

Return a vector of (f elem) for elements in coll. More than one collection may be supplied. If more than one collection is supplied, the function f will be passed sequential elements from each collection on each invocation and must be able to accept as many arguments as there are collections. The sequence will terminate when at least one input collection is exhausted.

fn (max & args)

Return the maximum of the arguments.

fn (max-key k & args)

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)

Expands into a function that calls the method name on the first argument of the resulting function. If args are provided, the resulting function will have arguments of these names.

This is a convenient way of producing a first-class function for a Python method.

fn (memoize f)

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)

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)

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 (meta o)

Return the metadata from o, or nil if there is no metadata.

fn (methods multifn)

Return a map of dispatch values to methods for the given multimethod.

fn (min & args)

Return the minimum of the arguments.

fn (min-key k & args)

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)

Returns the modulo of num and div.

It uses floored division for calculating the quotient.

multi fn (munge & args)

Munge the input value into a Python-safe string. Converts keywords and symbols into strings as by name prior to munging. Returns a string.

fn (name v)

Return the name of a string, symbol, or keyword.

fn (namespace v)

Return the namespace of a symbol or keyword, or nil if no namespace.

multi fn (namespace-munge & args)

Convert a Basilisp namespace name to a valid Python name.

fn (nat-int? x)

Return true if x is a non-negative integer

fn (neg-int? x)

Return true if x is a negative integer.

fn (neg? x)

Return true if x is negative.

macro (new class & args)

Create a new instance of class with args.

New objects may be created as any of:

(new python/str *args)
(new python.str *args)
(new python.str. *args)

This is compatibility syntax for Clojure, since Python (and therefore Basilisp) do not require the new keyword for object instantiation.

fn (newline)

Write a platform specific newline to *out*.

fn (next seq)

Calls rest on o. If o returns an empty sequence or nil, returns nil. Otherwise, returns the elements after the first in o.

fn (nfirst v)

Return the result of calling (next (first v)).

fn (nil? x)

Return true if x is nil, otherwise false.

fn (nnext v)

Return the result of calling (next (next v)).

fn (non-neg? x)

Return true if x is not negative.

fn (not expr)

Return the logical negation of expr.

fn (not-any? & args)

Return true if no element in coll satisfies pred.

fn (not-empty coll)

Return coll when coll is not empty, otherwise return nil.

fn (not-every? & args)

Return true if not every element in coll satisfies pred.

fn (not= & args)

Return true if x and y are not equal, otherwise false.

macro (ns name & opts)

Use this namespace pre-amble at the top of every namespace to declare the namespace name and import necessary Python modules and require Basilisp namespaces.

You may include an optional docstring for the namespace to describe its purpose. The docstring will be applied as the :doc key on the namespace metadata map.

Example:

(ns my.namespace
   "My namespace with code"
   (:refer-basilisp :exclude [get])
   (:require
     [basilisp.string :as str])
   (:use
     [basilisp.set :only [intersection]])
   (:import inspect))

Flags and contents of each of the various sections are detailed further at each of their respective function definitions.

  • :refer-basilisp (:refer-clojure is also accepted) controls how names from basilisp.core are exposed in the namespace. Refer to refer for usage.

  • :require imports other Basilisp namespaces. Refer to require for usage.

  • :use is a variant of :require, although :require is preferred in most cases. See use for usage.

  • :import imports Python modules and packages. Refer to import for usage.

Use of the ns macro to control requires and imports is recommended in all cases. The various functions that ns delegates to and whose documentation are referred to above are generally useful for interactive usage at the REPL but not appropriate for usage in a larger application.

fn (ns-aliases ns)

Return a map of Basilisp namespaces which are aliased in the current namespace.

fn (ns-imports ns)

Return a set of Python modules which are imported in the current namespace.

fn (ns-interns ns)

Return a map of symbols to Vars which are interned in the current namespace.

fn (ns-map)
fn (ns-map ns)

Return a map of all the mapped symbols in the namespace.

Includes the return values of ns-interns and ns-refers in one map.

fn (ns-name ns)

Return the name of the namespace, a symbol.

fn (ns-publics ns)

Return a map of symbols to public Vars which are interned in the current namespace.

Public vars are Vars which are declared without :private metadata.

fn (ns-refers ns)

Return a map of symbols to Vars which are referred in the current namespace.

fn (ns-resolve ns sym)

Return the Var which will be resolved by the symbol in the given namespace.

fn (ns-unalias ns sym)

Remove the alias for the symbol sym from ns. Return nil.

fn (ns-unmap ns sym)

Remove the mapping for the symbol sym from ns. Return nil.

fn (nth coll i)
fn (nth coll i notfound)

Returns the i th element of coll (0-indexed), if it exists or nil otherwise. If i is out of bounds, throws an IndexError unless notfound is specified.

coll may be any sequential collection type (such as a list or vector), string, or nil. If coll is not one of the supported types, a TypeError will be thrown.

fn (nthnext coll i)

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)

Returns the nth rest sequence of coll, or coll if i is 0.

(nthrest nil 1) ;=> nil (nthrest [] 1) ;=> [] (nthrest [1 2 3 4 5 6] 4) ;=> (5 6)

fn (number? x)

Return true if x is a number (integer, float, or complex).

fn (numerator frac)

Return the numerator of a Fraction.

fn (object-array size-or-seq)
fn (object-array size init-val-or-seq)

Create an array of objects.

If init-val-or-seq and is a seq yielding fewer than size elements, then the remaining indices of the resulting array will be filled with nil values.

This function does not coerce its argument and is provided for Clojure compatibility.

fn (odd? x)

Return true if x is odd.

macro (or)
macro (or & args)

Evaluate the expressions from left to right. Returns the first truthy expression. Otherwise, returns the final falsey expression. Calling or with no arguments returns nil.

fn (parents tag)
fn (parents h tag)

Return the set of all direct parents of tag in hierarchy h.

tag may be either a valid Python type or a namespace-qualified keyword or symbol. If tag is a Python type, ancestors include any relationships established via calls to derive as well as any immediate superclasses (as returned by bases). If tag is a namespace-qualified keyword, only relationships from derive are returned.

h must be a hierarchy returned by make-hierarchy. If h is not supplied, the global hierarchy will be used.

fn (parse-boolean s)

Parse the string argument s as either boolean true or false returning the boolean if the string contains one, or nil otherwise.

This function will throw a TypeError for non-string types.

fn (parse-double s)

Parse the string argument s as a floating point number as by Python’s builtin float function, returning the float if the string contains one, or nil otherwise.

This function will throw a TypeError for non-string types.

fn (parse-long s)

Parse the string argument s as an integer (base 10) as by Python’s builtin int function, returning the integer if the string contains one, or nil otherwise.

This function will throw a TypeError for non-string types.

fn (parse-uuid s)

Parse the string argument s as a UUID as by Python’s uuid.UUID, returning the UUID if the string contains one, or nil otherwise.

This function will throw a TypeError for non-string types.

fn (partial f)
fn (partial f & args)

Return a function which is the partial application of f with args.

fn (partial-kw f)
fn (partial-kw f m)
fn (partial-kw f arg & args)

Return a function which is the partial application of f with keyword arguments.

If a single argument is provided, it will be interpreted as a map of keyword arguments.

If multiple arguments are given, they are interpreted as key/value pairs and will be converted into a hash-map before being partially applied to the function.

This function applies keyword arguments via apply-kw. As a consequence, Lisp keywords will be converted to munged Python strings (via name), meaning namespaces will be lost and identifiers which are not valid Python syntax will be converted to safe Python identifiers.

fn (partition n coll)
fn (partition n step coll)
fn (partition n step pad coll)

Return a lazy sequence of partitions of coll of size n at offsets of step elements. If step is not given, steps of size n will be used and there will be no overlap between partitions. If pad is given, partition will pull elements from pad until the final sequence is equal to size n. If there are fewer than n leftover elements in coll, they will not be returned as a partial partition.

fn (partition-all n)
fn (partition-all n coll)
fn (partition-all n step coll)

Return a lazy sequence of partitions of coll of size n at offsets of step elements. If step is not given, steps of size n will be used and there will be no overlap between partitions. If there are leftover elements from coll which do not fill a full partition, then a partial partition will be returned, unlike partition.

Return a stateful transducer if no collection is provided.

fn (partition-by f)
fn (partition-by f coll)

Return a lazy sequence of partitions, splitting coll each time f returns a different value.

fn (pcalls & fns)

Return a lazy seq of the result of executing the no arg functions fns, which will be evaluated in parallel.

fn (peek coll)

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)

Return a persistent copy of the transient collection coll which was created by calling transient.

fn (pmap f coll)
fn (pmap f coll & colls)

Apply f as by map, 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 when pmap is first called, so it should be safe to bind in the initial calling thread. The sequence of futures is fed into a final (fully lazy) sequence to deref the Future and return its final value.

fn (pop coll)

For a list or a queue, return a new list without the first element.

For a vector, return a new vector without the last element.

If coll is empty, throw an exception.

fn (pop! coll)

Return a new transient vector without the last element of coll. If coll is empty, throw an exception.

fn (pop-thread-bindings)

Pop thread bindings set by a corresponding call to push-thread-bindings. This should not be called without a prior call to push-thread-bindings .

fn (pos-int? x)

Return true if x is a positive integer.

fn (pos? x)

Return true if x is positive.

dynamic Var pr

Print the arguments to the stream bound to *out* in a format which is readable by the Basilisp reader. Multiple arguments will be separated by the string value bound to *print-sep* (default is an ASCII space).

Note that some dynamically created Basilisp forms (such keywords and symbols) and Python objects may not be readable again.

It can be dynamically bound.

fn (pr-str & args)

Return the contents of calling pr on the args as a string.

fn (prefer-method multifn dispatch-val-x dispatch-val-y)

Update the mulitmethod multifn to prefer dispatch-val-x over dispatch-val-y in cases where the dispatch value selection might be ambiguous between the two.

Returns the multimethod.

fn (prefers multifn)

Return a map of the set of preferred values to the set of other conflicting values.

fn (print)
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 (print-str & args)

Return the contents of calling print on the args as a string.

fn (printf fmt & args)

Prints formatted output as per format.

Does not append a newline.

fn (println)
fn (println x)
fn (println x & args)

Print the arguments to the stream bound to *out* in a format which is readable by humans. println always prints a trailing newline. Multiple arguments will be separated by the string value bound to *print-sep* (default is an ASCII space).

Observes *flush-on-newline*.

fn (println-str & args)

Return the contents of calling println on the args as a string.

fn (prn)
fn (prn x)
fn (prn x & args)

Same as pr, but appending a newline afterwards.

Observes *flush-on-newline*.

fn (prn-str & args)

Return the contents of calling prn on the args as a string.

fn (promise)

Return a promise object which can be set exactly once using deliver . Readers may block waiting for the value of the promise using @ or deref. 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 using realized?.

fn (protocol? x)

Return true if x is a Protocol.

fn (push-thread-bindings bindings)

Takes a map of Var/value pairs and applies the given value to the Var in the current thread.

This call should be accompanied with a pop-thread-bindings call in a try / finally block.

This function is a very low level function and its use is discouraged in favor of a higher level construct like the binding macro.

macro (pvalues & exprs)

Returns a lazy seq of the result of exprs, which will be evaluated in parallel.

fn (py->lisp o)
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 to true. If `:keywordize-keys is ``true, then all string keys in Python dicts will be converted into keywords in the final return value.

fn (py-dict? x)

Return true if x is a Python dict.

fn (py-frozenset? x)

Return true if x is a Python frozenset.

fn (py-list? x)

Return true if x is a Python list.

fn (py-set? x)

Return true if x is a Python set.

fn (py-tuple? x)

Return true if x is a Python tuple.

fn (qualified-ident? x)

Return true if x is either a keyword or symbol with a namespace.

fn (qualified-keyword? x)

Return true if x is a keyword with a namespace.

fn (qualified-symbol? x)

Return true if x is a symbol with a namespace.

fn (queue)
fn (queue coll)

Return a new persistent queue.

fn (queue? x)

Return true if x is a persistent queue.

fn (quot num div)

Returns the quotient of num and div.

The division result is truncated.

fn (rand)
fn (rand upper)
fn (rand lower upper)

Return a random real number between lower (default: 0) and upper (default: 1) inclusive.

fn (rand-int upper)
fn (rand-int lower upper)

Return a random integer between lower (default: 0) and upper inclusive.

fn (rand-nth coll)

Return a random element from coll.

fn (random-sample prob)
fn (random-sample prob coll)

Return elements from coll with the random probability of prob.

Return a transducer if no collection is provided.

fn (random-uuid)

Return a random type 4 UUID.

fn (range)
fn (range end)
fn (range start end)
fn (range start end step)

Return a range of integers from start. If end is specified, the sequence will terminate at end.

fn (ratio? x)

Return true if x is a Fraction.

fn (rational? x)

Return true if x is a rational number.

fn (re-find pattern s)

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)

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)

Return a new re.Pattern instance.

fn (re-seq pattern s)

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)
fn (read stream)
fn (read opts stream)
fn (read stream eof-error? eof-value)

Read the next form from the stream. If no stream is specified, uses the value currently bound to *in*.

Callers may bind a map of readers to *data-readers* to customize the data readers used reading this string.

The stream must satisfy the interface of io.TextIOBase, but does not require any pushback capabilities. The default basilisp.lang.reader.StreamReader can wrap any object implementing TextIOBase and provide pushback capabilities.

fn (read-string s)
fn (read-string opts s)

Read a string of Basilisp code.

Callers may bind a map of readers to *data-readers* to customize the data readers used reading this string.

Note that read-string should not be used to read string input from untrusted sources. For reading EDN input from untrusted sources, instead consider using basilisp.edn.

fn (real-number? x)

Return true if x is a real number.

fn (realized? o)

Return true if the delay, future, lazy sequence, or promise has been realized.

fn (record? v)

Return true if v is a record type.

fn (reduce f coll)
fn (reduce f val coll)

Reduce coll by f.

If val is not supplied and coll has no elements, f will be called with no arguments and the result will be returned.

If val is not supplied and coll has one element, the result of (f (first val)) is returned.

If val is not supplied and coll has elements, repeatedly reduce coll by calling f on successive elements in coll.

If val is supplied and coll has no elements, return val` and ``f will not be called.

If val is supplied and coll has elements, repeatedly reduce coll by calling f on successive elements in coll, starting with val.

If f returns a reduced value at any point, reduction will terminate and the reduced value will be returned immediately.

fn (reduce-kv f init coll)

Reduce an associative coll by f. f must be a function of 3 arguments: the initially supplied value init (in later invocations, the return from previous invocations), the key of an entry of coll, and the value of an entry of coll.

If coll has no elements, init is returned and f is not called.

If f returns a reduced value at any point, reduction will terminate and the reduced value will be returned immediately.

reduce-kv may reduce vectors in addition to maps. Vectors have non-negative integer keys.

fn (reduced x)

Wraps a value x such that it will terminate a reduce operation.

Callers can retrieve the inner reduced value using deref or @x.

fn (reduced? x)

Return true if x should be considered fully reduced.

fn (refer ns-sym & filters)

Refer Vars from the namespace named by ns-sym, subject to the filters specified.

Supported filters:

  • :only [sym1 sym2] to only refer the specified symbols

  • :exclude [sym1, sym2] to refer all except the specified symbols

  • :rename {sym1 new-sym1} to rename all the specified symbols to the given new name

Use of refer directly is discouraged in favor of the :refer modifier in the :require directive of the ns macro or the :use directive of the ns macro.

fn (refer-basilisp & args)

Refer Vars from basilisp.core using the same filter syntax as refer.

fn (refer-clojure & args)

Compatibility layer with JVM Clojure, which points to refer-basilisp.

macro (reify & method-impls)

Create a new Python object of an anonymous type which implements 0 or more Python interfaces or Basilisp protocols.

Unlike types created via deftype, reify returns an object which implements the named interfaces using the implementations provided. You may not provide fields as such to reify, though reify closes over any local names defined in the same lexical context. These fields may serve as private fields of the created object.

Interface or protocol implementations are declared as the name of the interface or protocol as a symbol, followed by 1 or more method definitions for that interface. Types are not required to declare any interface implementations. Types which do declare interface implementations are required to implement all interface methods. Failing to implement all interface methods is a compile time error. Types implementing object are not required to implement all object methods.

Method declarations should appear as:

(method-name [arg1] & body)
(method-name [arg1 arg2 ...] & body)

Unlike in Clojure, interface and protocol methods are permitted to include variadic arguments. Single-arity methods may also declare support for keyword arguments using either the :apply or :collect strategy on the :kwargs metadata on the method name. Finally, single-arity methods may be declared as Python properties using the :property metadata on the method name. These facilities are provided as a means to interoperate with Python code and their use is discouraged in pure Basilisp code.

reify does not support class method or static method members and attempting to declare reify members as class or static members will result in a compile time error.

Type objects are created with sensible object defaults as by attrs. New types may override object defaults.

Reified objects always implement basilisp.lang.interfaces/IWithMeta and transfer the metadata from the form to the created object.

Methods must supply a this or self parameter. recur special forms used in the body of a method should not include that parameter, as it will be supplied automatically.

fn (rem num div)

Returns the remainder of num and div.

It uses truncated division for calculating the quotient.

fn (remove pred)
fn (remove pred coll)

Return elements from coll where (pred elem) returns a falsey value.

Return a transducer if no collection is provided.

fn (remove-all-methods multifn)

Remove all methods for the multimethod multifn.

Return the multimethod.

fn (remove-method multifn dispatch-val)

Remove the method from the multimethod multifn which responds to dispatch-val, if it exists.

Return the multimethod.

fn (remove-ns ns-sym)

Remove the namespace named by the symbol.

fn (remove-tap tf)
fn (remove-tap topic tf)

Remove a tap function from the tap set added by add-tap.

Tap functions may only be removed from the tap set corresponding to the topic they were added with. If no topic is given, the default topic is used.

Returns nil in all cases.

fn (remove-watch ref k)

Remove the watch function identified by k from the ref (Atom or Var), if it exists. Returns the ref.

fn (repeat x)
fn (repeat n x)

Repeat x infinitely or n many times if n is specified. Returns a lazy sequence of the x.

fn (repeatedly f)
fn (repeatedly n f)

Call f infinitely or n many times if n is specified. Returns a lazy sequence of the return values.

fn (replace smap)
fn (replace smap coll)

Replace elements of the vector/seq coll with matching elements from the associative collection smap, if they exist.

Return a transducer if no collection is provided.

fn (repr x)

Return the reader representation of an object.

fn (require & args)

Load Basilisp libraries and make them accessible in the current namespace.

Arguments should be libspecs, which take the following forms:

  • symbols, which name fully qualified namespaces

  • vectors, which take the form [namespace-symbol & opts]

Vector libspec arguments must be one of:

  • :as name which will alias the imported namespace to the symbol name

  • :as-alias name which will alias the namespace to the symbol name but not require the namespace, which can be useful for namespaces used primarily for keywords; the namespace need not exist at all; can be combined with :as

  • :refer [& syms] which will refer syms in the local namespace directly

  • :refer :all which will refer all symbols from the namespace directly

Use of require directly is discouraged in favor of the :require directive in the ns macro.

fn (requiring-resolve sym)

Resolve the namespaced symbol sym as by resolve. If resolution fails, attempts to require sym ‘s namespace (as by require) before resolving again.

fn (reset! atom v)

Reset the value of an atom to v without regard to the previous value. Return the new value.

fn (reset-meta! o meta)

Atomically swap the metadata on reference o to meta. References include atoms, namespaces, and vars.

fn (reset-vals! atom v)

Reset the value of an atom to v without regard to the previous value. Return a vector containing the new value and the old value in that order.

fn (resolve sym)

Return the Var which will be resolved by the symbol in the namespace currently bound to *ns*.

fn (rest seq)

If seq is a Seq, return the elements after the first in seq. If seq is nil, returns an empty seq. Otherwise, coerces seq to a seq and returns the rest.

fn (reverse coll)

Return a seq containing the elements in coll in reverse order. The returned sequence is not lazy.

fn (reversible? x)

Return true if x implements IReversible.

fn (rseq coll)

Return a sequence of the elements of coll in reverse order in constant time. Only Vectors support this operation.

fn (satisfies? {:as proto :keys [interface impls]} x)

Return true if x satisfies protocol proto.

fn (second seq)

Returns the second element in a Seq.

fn (select-keys m ks)

Return a map with only the keys of m which are in ks.

fn (seq o)

Coerce the argument o to a Seq. If o is nil, return nil.

fn (seq? o)

Return true if o implements Seq.

fn (seqable? x)

Return true if an ISeq can be produced from x.

fn (sequence coll)
fn (sequence xform coll)
fn (sequence xform coll & colls)

Coerces coll to a possibly empty sequence. If coll is nil, return ().

When a transducer xform is supplied, returns a lazy sequence of the transform to elements of coll. If multiple collections are provided, xform must support as many arguments as there are collections.

If multiple collections are provided, the resulting sequence will terminate when any one of the inputs is exhausted.

fn (sequential? x)

Return true if x implements ISequential.

fn (set coll)

Return a set with the contents of coll.

fn (set-validator! ref vf)

Set the validator function for the ref (Atom or Var).

Validator functions should be side-effect free functions of one argument: the proposed new value of the ref. The validator should either return false or throw an error if the ref value is invalid.

nil may be passed to remove the validator for a ref.

If the existing ref value is not valid according to vf, an exception will be thrown and the new validator function will not be applied.

fn (set? o)

Return true if o is a set.

fn (short x)

Coerce x to an integer.

Python does not support short types, so the value is coerced to an integer.

fn (shorts x)

Dummy cast to a Python list of shorts.

This function is provided for Clojure compatibility.

fn (shuffle coll)

Return a random permutation of coll.

fn (simple-keyword? x)

Return true if x is a keyword with no namespace.

fn (simple-symbol? x)

Return true if x is a symbol with no namespace.

fn (slurp f & opts)

Open a basilisp.io/reader instance on f and read the contents of f into a string.

Options may be provided as key value pairs and will be passed directly to basilisp.io/reader. Supported reader options depend on which type of reader is selected for f. Most readers support the :encoding option.

If f is a string, it first is resolved as a URL (via urllib.parse.urlparse). If the URL is invalid or refers to a filesystem location (via file:// scheme), then it will be resolved as a local filesystem path.

Return the string contents.

fn (some pred coll)

Return true if at least one element in coll satisfies pred.

macro (some-> x & forms)

Thread x through the forms (as by ->) until the resulting expression is nil or there are no more forms.

macro (some->> x & forms)

Thread x through the forms (as by ->>) until the resulting expression is nil or there are no more forms.

fn (some-fn f)
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 (some? x)

Return true if x is not nil, otherwise false s.

fn (sort coll)
fn (sort cmp coll)

Return a sorted sequence of the elements from coll using the cmp comparator.

The compare fn is used in if cmp is not provided.

fn (sort-by keyfn coll)
fn (sort-by keyfn cmp coll)

Return a sorted sequence of the elements from coll using the cmp comparator on (keyfn item).

The compare fn is used in if cmp is not provided.

fn (special-symbol? x)

Return true if x is a special form symbol.

fn (spit f content & opts)

Open a basilisp.io/writer instance on f and write content out to f before closing the writer.

Options may be provided as key value pairs and will be passed directly to basilisp.io/writer. Supported writer options depend on which type of writer is selected for f. Most writers support the :encoding option.

If f is a string, it first is resolved as a URL (via urllib.parse.urlparse). If the URL is invalid or refers to a filesystem location (via file:// scheme), then it will be resolved as a local filesystem path.

spit does not support writing to non-file URLs.

Return nil.

fn (split-at n coll)

Split a collection at the n th item. Returns a vector of [(take n coll) (drop n coll)].

fn (split-with pred coll)

Split a collection at the inflection point of pred. Returns a vector of [(take-while pred coll) (drop-while pred coll)].

fn (str)
fn (str o)
fn (str o & args)

Create a string representation of o.

Return the empty string if o is nil.

fn (string? o)

Return true if o is a string.

fn (subclasses cls)

Return a set of subclasses of cls.

This set is not guaranteed to be exhaustive because classes only retain a weak reference to their subclasses, so it is possible subclasses of cls have been garbage collected.

fn (subs s start)
fn (subs s start end)

Return a substring of s from the index start (inclusive) to index end exclusive, or the end of the string if no end is supplied.

fn (subvec v start)
fn (subvec v start end)

Return a vector of elements consisting of the elements of v from the index start (inclusive) to index end exclusive, or the end of the vector if no end is supplied.

fn (supers cls)

Return the direct and indirect superclasses and interfaces of cls as a set.

fn (swap! atom f & args)

Atomically swap the value of an atom to the return value of (apply f current-value args). The function f may be called multiple times while swapping, so should be free of side effects. Return the new value.

fn (swap-vals! atom f & args)

Atomically swap the value of an atom to the return value of (apply f current-value args) . The function ``f` may be called multiple times while swapping, so should be free of side effects. Return a vector containing the new value and the old value in that order.

fn (symbol name)
fn (symbol ns name)

Create a new symbol with name and optional namespace ns.

fn (symbol? o)

Return true if o is a symbol.

fn (take n)
fn (take n coll)

Return the first n elements of coll.

fn (take-last n coll)

Return the last n items in coll in linear time.

fn (take-nth n)
fn (take-nth n coll)

Return a lazy sequence of every n th element of coll.

Return a stateful transducer if no collection is provided.

fn (take-while pred)
fn (take-while pred coll)

Return elements of coll while (pred elem) is true.

Return a transducer if no collection is provided.

fn (tap> val)
fn (tap> topic val)

Send the value val to all tap functions registered for the topic. If no topic is given, the default topic is used.

tap> will never block, though if the tap queue is full then tap values may be dropped.

Returns true if val was sent to the queue, false if val was dropped.

fn (the-ns v)

If v is a symbol, return the Namespace named by that symbol if it exists. If v is a Namespace, return it. Otherwise, throw an exception.

fn (thread-bound? & vars)

Return true if vars are thread-bound, which implies that a set! will succeed. Returns true if no vars are given.

macro (time expr)

Time the execution of expr. Return the result of expr and print the time execution took in milliseconds.

fn (to-array coll)

Return a Python list with the contents of coll.

fn (to-array-2d coll)

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)

Trampoline f with starting arguments. If f returns a function (as determined by fn?), call its return value with no arguments, repeating that process until the return value is not a function.

fn (transduce xform f coll)
fn (transduce xform f init coll)

Reduce coll by the transducing function xf (created as (xform f)).

If coll is empty, return init without calling f. If init is not given, f will be called with no arguments to produce it.

The transducing process will eagerly consume the input collection, calling xf on the result of the previous call (or init on the first invocation) and the next value from the input collection, until either the collection is exhausted or xf returns a reduced value. In both cases, the xf ‘s 1-arity will be called with result and that result will be returned.

fn (transient coll)

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!, and pop!. 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)

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 return true if a node might contain children (though it need not).

children should be a function of one argument which should return a sequence of children of a node. children will only be called on a node if branch? returns true for that node.

fn (true? x)

Return true if x is true, otherwise false.

fn (type x)

Return the type of x.

fn (unchecked-add)
fn (unchecked-add x)
fn (unchecked-add x y)
fn (unchecked-add x y & args)

Sum the arguments together. If no arguments given, returns 0.

Same as +. Python integers are unlimited precision, so unchecked

arithmetic is onlyprovided for compatibility with platforms without unlimited precision integers.

fn (unchecked-add-int)
fn (unchecked-add-int x)
fn (unchecked-add-int x y)
fn (unchecked-add-int x y & args)

Sum the arguments together. If no arguments given, returns 0.

Same as +. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-byte x)

Coerce x to a byte. Value may be truncated or rounded.

fn (unchecked-char x)

Coerce x to a char. Value may be truncated or rounded.

fn (unchecked-dec x)

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.

fn (unchecked-dec-int x)

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.

fn (unchecked-divide-int x)
fn (unchecked-divide-int x y)
fn (unchecked-divide-int x y & args)

Divide the arguments. If no arguments given, returns the inverse of the argument.

Same as /. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-double x)

Coerce x to a float.

Python does not differentiate between float and double. Python float s are double precision.

Same as double. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-float x)

Coerce x to a float.

If x is string, it is parsed as a floating point number.

Same as float. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-inc x)

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.

fn (unchecked-inc-int x)

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.

fn (unchecked-int x)

Coerce x to an integer.

If x is string, it is parsed as a base 10 number.

Same as int. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-long x)

Coerce x to an integer.

Python does not support long types, so the value is coerced to an integer.

Same as long. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-multiply)
fn (unchecked-multiply x)
fn (unchecked-multiply x y)
fn (unchecked-multiply x y & args)

Multiply the arguments. If no arguments given, returns 1.

Same as *. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-multiply-int)
fn (unchecked-multiply-int x)
fn (unchecked-multiply-int x y)
fn (unchecked-multiply-int x y & args)

Multiply the arguments. If no arguments given, returns 1.

Same as *. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-negate x)

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)

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)

Coerce x to an integer.

Python does not support short types, so the value is coerced to an integer.

Same as short. Python integers are unlimited precision, so unchecked

arithmetic is only provided for compatibility with platforms without unlimited precision integers.

fn (unchecked-subtract x)
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)
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)
fn (underive h tag parent)

Remove a parent/child relationship between tag and parent originally created via derive.

tag may be either a valid Python type or a namespace-qualified keyword or symbol.

parent must be a namespace-qualified keyword or symbol.

h must be a hierarchy returned by make-hierarchy. If h is not supplied, the global hierarchy will be used.

Var unquote

Placeholder Var so the compiler does not throw an error while syntax quoting.

See Macros and Syntax Quoting for more details.

Var unquote-splicing

Placeholder Var so the compiler does not throw an error while syntax quoting.

See Macros and Syntax Quoting for more details.

fn (unreduced x)

If x is a reduced value (as produced by reduced), unwrap it and return the inner value. Otherwise return x.

fn (update m k f & args)

Updates the value for key k in associative data structure m with the return value from calling (f old-v & args). If m is nil, use an empty map. If k is not in m, old-v will be nil.

fn (update-in m ks f & args)

Updates the value for key k in associative data structure m with the return value from calling (f old-v & args). If m is nil, use an empty map. If k is not in m, old-v will be nil.

fn (update-keys m f)

Update the keys in map m by applying a function of one argument, f, to every key.

f must return a unique key for every input key, otherwise the behavior of this function is undefined.

fn (update-vals m f)

Update the values in map m by applying a function of one argument, f, to every value.

fn (use & args)

Load Basilisp libraries and make them accessible in the current namespace.

Arguments should be libspecs, which take the following forms:

  • symbols, which name fully qualified namespaces

  • vectors, which take the form [namespace-symbol & opts]

use is like require which also refers all Vars from the requiring Namespace afterwards. Libspecs passed to use may include filters as defined in refer to narrow down the referred Vars.

Supported filters:

  • :only [sym1 sym2] to only refer the specified symbols

  • :exclude [sym1, sym2] to refer all except the specified symbols

  • :rename {sym1 new-sym1} to rename all the specified symbols to the given new name

Use of use directly is discouraged in favor of the :use directive in the ns macro.

fn (uuid-like? x)

Return true if x is coercible to a UUID.

Python’s UUID constructor supports byte sequences in big- and little-endian byte orders. This function checks only for big-endian bytes.

fn (uuid? x)

Return true if x is a UUID.

fn (val entry)

Return the val from a map entry.

fn (vals m)

Return a seq of the values from a map.

fn (var-get v)

Return the value inside the Var. Return thread local bindings if they exist, otherwise, return the root binding.

fn (var-set v val)

Set the binding of the Var. Must be thread-local.

fn (var? x)

Return true if x is a Var.

fn (vary-meta o f & args)

Return an object of the same type and representing the same value as o (as by with-meta) with the new object’s metadata set to the value of (apply f (meta o) & args).

fn (vec coll)

Return a vector with the contents of coll.

fn (vector & elems)

Create a vector from the input arguments.

fn (vector? o)

Return true if o is a vector.

fn (volatile! v)

Return a Volatile reference container with the initial value v.

fn (volatile? x)

Return true if x is a volatile reference container.

fn (vreset! v new-val)

Reset the value of volatile v non-atomically to new-val. Returns the new value.

fn (vswap! v f & args)

Swap the value of volatile v non-atomically to the return of (apply f old-val args). Returns the new value of that function call.

macro (when cond & body)

Evaluate cond and if it is truthy, execute body in an implicit do block.

macro (when-first binding & body)

Evaluate the binding as with let, binding the given name to the first value (as by first) in the binding expression iff the first value in the binding expression is not nil. Return nil otherwise.

macro (when-let binding & body)

Evaluate the binding as with let, binding the given name for use in the true expression iff the binding expression is truthy. Return nil otherwise.

macro (when-not cond & body)

Evaluate cond and if it is falsey, execute body in an implicit do block.

macro (when-some binding & body)

Evaluate the binding as with let, binding the given name for use in the true expression iff the binding expression is not nil. Return nil otherwise.

macro (while cond & body)

Execute body repeatedly (likely for side effects) until cond returns false. Return nil.

macro (with bindings & body)

Evaluate body within a try / except expression, binding the named expressions as per Python’s context manager protocol spec (Python’s with blocks).

macro (with-bindings bindings-map & body)

Execute the expressions given in the body with the thread-local Var bindings specified in the Var/value map bindings-map installed.

The thread-local Var bindings will be popped after executing the body in all cases.

Returns the value of body.

fn (with-bindings* bindings-map f & args)

Execute the function f with the given arguments args (as by apply) with the thread-local Var bindings specified in the Var/value map bindings-map installed.

The thread-local Var bindings will be popped after executing f in all cases.

Returns the return value of f.

macro (with-in-str s & body)

Evaluate body with *in* bound to a io.StringIO instance containing the string s.

fn (with-meta o meta)

Return an object of the same type and representing the same value as o with meta as its metadata. Of Basilisp’s builtin types, only those implementing the interface IWithMeta support with-meta.

macro (with-open & args)

Evaluate body within a try / except expression, binding the named expressions as per Python’s context manager protocol spec (Python’s with blocks).

macro (with-out-str & body)

Capture the contents of text sent to *out* and return the contents as a string.

macro (with-redefs bindings & body)

Temporarily re-bind the given Var roots to the given values while executing the body, binding back to the original value afterwards.

Changes to the Var roots will be visible in all threads.

Note that Basilisp directly links Var references in compiled code by default for performance reasons. Direct linking can be disabled for all Vars during compilation by setting the --use-var-indirection compiler flag at startup. Direct linking can be disabled for individual Vars by setting the ^:redef meta flag where the Var is def ‘ed.

with-redefs will throw an Exception if directly linked Vars are given in the bindings.

fn (with-redefs-fn bindings-map f)

Temporarily re-bind the given Var roots to the given values while executing the function f, binding back to the original value afterwards.

Changes to the Var roots will be visible in all threads.

Note that Basilisp directly links Var references in compiled code by default for performance reasons. Direct linking can be disabled for all Vars during compilation by setting the --use-var-indirection compiler flag at startup. Direct linking can be disabled for individual Vars by setting the ^:redef meta flag where the Var is def ‘ed.

with-redefs-fn will throw an Exception if directly linked Vars are given in the bindings.

fn (zero? x)

Return true if x is 0.

fn (zipmap keys vals)

Return a map with the keys mapped to their corresponding indexed value in vals.