API

(eval hytree locals module ast-callback compiler filename source [import-stdlib True])

Evaluates a quoted expression and returns the value.

If you’re evaluating hand-crafted AST trees, make sure the line numbers are set properly. Try fix_missing_locations and related functions in the Python ast library.

Examples

=> (hy.eval '(print "Hello World"))
"Hello World"

If you want to evaluate a string, use read-str to convert it to a form first:

=> (hy.eval (read-str "(+ 1 1)"))
2
Parameters
  • hytree (hy.models.Object) – The Hy AST object to evaluate.

  • locals (dict, optional) – Local environment in which to evaluate the Hy tree. Defaults to the calling frame.

  • module (str or types.ModuleType, optional) – Module, or name of the module, to which the Hy tree is assigned and the global values are taken. The module associated with compiler takes priority over this value. When neither module nor compiler is specified, the calling frame’s module is used.

  • ast_callback (callable, optional) – A callback that is passed the Hy compiled tree and resulting expression object, in that order, after compilation but before evaluation.

  • compiler (HyASTCompiler, optional) – An existing Hy compiler to use for compilation. Also serves as the module value when given.

  • filename (str, optional) – The filename corresponding to the source for tree. This will be overridden by the filename field of tree, if any; otherwise, it defaults to “<string>”. When compiler is given, its filename field value is always used.

  • source (str, optional) – A string containing the source code for tree. This will be overridden by the source field of tree, if any; otherwise, if None, an attempt will be made to obtain it from the module given by module. When compiler is given, its source field value is always used.

Returns

Result of evaluating the Hy compiled tree.

Special Forms

^

The ^ symbol is used to denote annotations in three different contexts:

  • Standalone variable annotations.

  • Variable annotations in a setv call.

  • Function argument annotations.

They implement PEP 526 and PEP 3107.

Here is some example syntax of all three usages:

Examples

; Annotate the variable x as an int (equivalent to `x: int`).
(^int x)
; Can annotate with expressions if needed (equivalent to `y: f(x)`).
(^(f x) y)

; Annotations with an assignment: each annotation (int, str) covers the term that
; immediately follows.
; Equivalent to: x: int = 1; y = 2; z: str = 3
(setv ^int x 1 y 2 ^str z 3)

; Annotate a as an int, c as an int, and b as a str.
; Equivalent to: def func(a: int, b: str = None, c: int = 1): ...
(defn func [^int a ^str [b None] ^int [c 1]] ...)

The rules are:

  • The value to annotate with is the value that immediately follows the caret.

  • There must be no space between the caret and the value to annotate, otherwise it will be interpreted as a bitwise XOR like the Python operator.

  • The annotation always comes (and is evaluated) before the value being annotated. This is unlike Python, where it comes and is evaluated after the value being annotated.

Note that variable annotations are only supported on Python 3.6+.

For annotating items with generic types, the of macro will likely be of use.

Note

Since the addition of type annotations, identifiers that start with ^ are considered invalid as hy would try to read them as types.

.

New in version 0.10.0.

. is used to perform attribute access on objects. It uses a small DSL to allow quick access to attributes and items in a nested data structure.

Examples

(. foo bar baz [(+ 1 2)] frob)

Compiles down to:

foo.bar.baz[1 + 2].frob

. compiles its first argument (in the example, foo) as the object on which to do the attribute dereference. It uses bare symbols as attributes to access (in the example, bar, baz, frob), and compiles the contents of lists (in the example, [(+ 1 2)]) for indexation. Other arguments raise a compilation error.

Access to unknown attributes raises an AttributeError. Access to unknown keys raises an IndexError (on lists and tuples) or a KeyError (on dictionaries).

(fn name #* arags)

fn, like Python’s lambda, can be used to define an anonymous function. Unlike Python’s lambda, the body of the function can comprise several statements. The parameters are similar to defn: the first parameter is vector of parameters and the rest is the body of the function. fn returns a new function. In the following example, an anonymous function is defined and passed to another function for filtering output:

=> (setv people [{:name "Alice" :age 20}
...             {:name "Bob" :age 25}
...             {:name "Charlie" :age 50}
...             {:name "Dave" :age 5}])

=> (defn display-people [people filter]
...  (for [person people] (if (filter person) (print (:name person)))))

=> (display-people people (fn [person] (< (:age person) 25)))
Alice
Dave

Just as in normal function definitions, if the first element of the body is a string, it serves as a docstring. This is useful for giving class methods docstrings:

=> (setv times-three
...   (fn [x]
...    "Multiplies input by three and returns the result."
...    (* x 3)))

This can be confirmed via Python’s built-in help function:

=> (help times-three)
Help on function times_three:

times_three(x)
Multiplies input by three and returns result
(END)
(fn/a name #* args)

fn/a is a variant of fn than defines an anonymous coroutine. The parameters are similar to defn/a: the first parameter is vector of parameters and the rest is the body of the function. fn/a returns a new coroutine.

(await obj)

await creates an await expression. It takes exactly one argument: the object to wait for.

Examples

=> (import asyncio)
=> (defn/a main []
...    (print "hello")
...    (await (asyncio.sleep 1))
...    (print "world"))
=> (asyncio.run (main))
hello
world
(break)

break is used to break out from a loop. It terminates the loop immediately. The following example has an infinite while loop that is terminated as soon as the user enters k.

Examples

=> (while True
...   (if (= "k" (input "? "))
...       (break)
...       (print "Try again")))
(cmp #* args)

cmp creates a comparison expression. It isn’t required for unchained comparisons, which have only one comparison operator, nor for chains of the same operator. For those cases, you can use the comparison operators directly with Hy’s usual prefix syntax, as in (= x 1) or (< 1 2 3). The use of cmp is to construct chains of heterogeneous operators, such as x <= y < z. It uses an infix syntax with the general form

(cmp ARG OP ARG OP ARG…)

Hence, (cmp x <= y < z) is equivalent to (and (<= x y) (< y z)), including short-circuiting, except that y is only evaluated once.

Each ARG is an arbitrary form, which does not itself use infix syntax. Use py if you want fully Python-style operator syntax. You can also nest cmp forms, although this is rarely useful. Each OP is a literal comparison operator; other forms that resolve to a comparison operator are not allowed.

At least two ARGs and one OP are required, and every OP must be followed by an ARG.

As elsewhere in Hy, the equality operator is spelled =, not == as in Python.

(continue)

continue returns execution to the start of a loop. In the following example, (side-effect1) is called for each iteration. (side-effect2), however, is only called on every other value in the list.

Examples

=> ;; assuming that (side-effect1) and (side-effect2) are functions and
=> ;; collection is a list of numerical values
=> (for [x collection]
...   (side-effect1 x)
...   (if (% x 2)
...     (continue))
...   (side-effect2))
(do #* body)

do (called progn in some Lisps) takes any number of forms, evaluates them, and returns the value of the last one, or None if no forms were provided.

Examples

=> (+ 1 (do (setv x (+ 1 1)) x))
3
(for #* args)

for is used to evaluate some forms for each element in an iterable object, such as a list. The return values of the forms are discarded and the for form returns None.

=> (for [x [1 2 3]]
...  (print "iterating")
...  (print x))
iterating
1
iterating
2
iterating
3

In its square-bracketed first argument, for allows the same types of clauses as lfor.

=> (for [x [1 2 3]  :if (!= x 2)  y [7 8]]
...  (print x y))
1 7
1 8
3 7
3 8

Furthermore, the last argument of for can be an (else …) form. This form is executed after the last iteration of the for's outermost iteration clause, but only if that outermost loop terminates normally. If it’s jumped out of with e.g. break, the else is ignored.

=> (for [element [1 2 3]] (if (< element 3)
...                             (print element)
...                             (break))
...    (else (print "loop finished")))
1
2

=> (for [element [1 2 3]] (if (< element 4)
...                             (print element)
...                             (break))
...    (else (print "loop finished")))
1
2
3
loop finished
(assert condition [label None])

assert is used to verify conditions while the program is running. If the condition is not met, an AssertionError is raised. assert may take one or two parameters. The first parameter is the condition to check, and it should evaluate to either True or False. The second parameter, optional, is a label for the assert, and is the string that will be raised with the AssertionError. For example:

Examples

(assert (= variable expected-value))

(assert False)
; AssertionError

(assert (= 1 2) "one should equal two")
; AssertionError: one should equal two
(global sym)

global can be used to mark a symbol as global. This allows the programmer to assign a value to a global symbol. Reading a global symbol does not require the global keyword – only assigning it does.

The following example shows how the global symbol a is assigned a value in a function and is later on printed in another function. Without the global keyword, the second function would have raised a NameError.

Examples

(defn set-a [value]
  (global a)
  (setv a value))

(defn print-a []
  (print a))

(set-a 5)
(print-a)
(get coll key1 #* keys)

get is used to access single elements in collections. get takes at least two parameters: the data structure and the index or key of the item. It will then return the corresponding value from the collection. If multiple index or key values are provided, they are used to access successive elements in a nested structure. Example usage:

:string:`Examples`

=> (do
...  (setv animals {"dog" "bark" "cat" "meow"}
...        numbers (, "zero" "one" "two" "three")
...        nested [0 1 ["a" "b" "c"] 3 4])
...  (print (get animals "dog"))
...  (print (get numbers 2))
...  (print (get nested 2 1)))

bark
two
b

Note

get raises a KeyError if a dictionary is queried for a non-existing key.

Note

get raises an IndexError if a list or a tuple is queried for an index that is out of bounds.

(import #* forms)

import is used to import modules, like in Python. There are several ways that import can be used.

Examples

;; Imports each of these modules
;;
;; Python:
;; import sys
;; import os.path
(import sys os.path)

;; Import from a module
;;
;; Python: from os.path import exists, isdir, isfile
(import [os.path [exists isdir isfile]])

;; Import with an alias
;;
;; Python: import sys as systest
(import [sys :as systest])

;; You can list as many imports as you like of different types.
;;
;; Python:
;; from tests.resources import kwtest, function_with_a_dash
;; from os.path import exists, isdir as is_dir, isfile as is_file
;; import sys as systest
(import [tests.resources [kwtest function-with-a-dash]]
        [os.path [exists
                  isdir :as dir?
                  isfile :as file?]]
        [sys :as systest])

;; Import all module functions into current namespace
;;
;; Python: from sys import *
(import [sys [*]])
(eval-and-compile #* body)

eval-and-compile is a special form that takes any number of forms. The input forms are evaluated as soon as the eval-and-compile form is compiled, instead of being deferred until run-time. The input forms are also left in the program so they can be executed at run-time as usual. So, if you compile and immediately execute a program (as calling hy foo.hy does when foo.hy doesn’t have an up-to-date byte-compiled version), eval-and-compile forms will be evaluated twice.

One possible use of eval-and-compile is to make a function available both at compile-time (so a macro can call it while expanding) and run-time (so it can be called like any other function):

(eval-and-compile
  (defn add [x y]
    (+ x y)))

(defmacro m [x]
  (add x 2))

(print (m 3))     ; prints 5
(print (add 3 6)) ; prints 9

Had the defn not been wrapped in eval-and-compile, m wouldn’t be able to call add, because when the compiler was expanding (m 3), add wouldn’t exist yet.

(eval-when-compile #* body)

eval-when-compile is like eval-and-compile, but the code isn’t executed at run-time. Hence, eval-when-compile doesn’t directly contribute any code to the final program, although it can still change Hy’s state while compiling (e.g., by defining a function).

Examples

(eval-when-compile
  (defn add [x y]
    (+ x y)))

(defmacro m [x]
  (add x 2))

(print (m 3))     ; prints 5
(print (add 3 6)) ; raises NameError: name 'add' is not defined
(lfor binding iterable #* body)

The comprehension forms lfor, sfor, dfor, gfor, and for are used to produce various kinds of loops, including Python-style comprehensions. lfor in particular creates a list comprehension. A simple use of lfor is:

=> (lfor x (range 5) (* 2 x))
[0, 2, 4, 6, 8]

x is the name of a new variable, which is bound to each element of (range 5). Each such element in turn is used to evaluate the value form (* 2 x), and the results are accumulated into a list.

Here’s a more complex example:

=> (lfor
...  x (range 3)
...  y (range 3)
...  :if (!= x y)
...  :setv total (+ x y)
...  [x y total])
[[0, 1, 1], [0, 2, 2], [1, 0, 1], [1, 2, 3], [2, 0, 2], [2, 1, 3]]

When there are several iteration clauses (here, the pairs of forms x (range 3) and y (range 3)), the result works like a nested loop or Cartesian product: all combinations are considered in lexicographic order.

The general form of lfor is:

(lfor CLAUSES VALUE)

where the VALUE is an arbitrary form that is evaluated to produce each element of the result list, and CLAUSES is any number of clauses. There are several types of clauses:

  • Iteration clauses, which look like LVALUE ITERABLE. The LVALUE is usually just a symbol, but could be something more complicated, like [x y].

  • :async LVALUE ITERABLE, which is an asynchronous form of iteration clause.

  • :do FORM, which simply evaluates the FORM. If you use (continue) or (break) here, they will apply to the innermost iteration clause before the :do.

  • :setv LVALUE RVALUE, which is equivalent to :do (setv LVALUE RVALUE).

  • :if CONDITION, which is equivalent to :do (unless CONDITION (continue)).

For lfor, sfor, gfor, and dfor, variables are scoped as if the comprehension form were its own function, so variables defined by an iteration clause or :setv are not visible outside the form. In fact, these forms are implemented as generator functions whenever they contain Python statements, with the attendant consequences for calling return. By contrast, for shares the caller’s scope.

(dfor binding iterable #* body)

dfor creates a dictionary comprehension. Its syntax is the same as that of :hy:macro:`lfor except that the final value form must be a literal list of two elements, the first of which becomes each key and the second of which becomes each value.

Examples

=> (dfor x (range 5) [x (* x 10)])
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
(gfor binding iterable #* body)

gfor creates a generator expression. Its syntax is the same as that of lfor. The difference is that gfor returns an iterator, which evaluates and yields values one at a time.

Examples

=> (setv accum [])
=> (list (take-while
...  (fn [x] (< x 5))
...  (gfor x (count) :do (.append accum x) x)))
[0, 1, 2, 3, 4]
=> accum
[0, 1, 2, 3, 4, 5]
(sfor binding iterable #* body)

sfor creates a set comprehension. (sfor CLAUSES VALUE) is equivalent to (set (lfor CLAUSES VALUE)). See lfor.

(setv #* args)

setv is used to bind a value, object, or function to a symbol.

Examples

=> (setv names ["Alice" "Bob" "Charlie"])
=> (print names)
[u'Alice', u'Bob', u'Charlie']

=> (setv counter (fn [collection item] (.count collection item)))
=> (counter [1 2 3 4 5 2 3] 2)
2

You can provide more than one target–value pair, and the assignments will be made in order:

=> (setv  x 1  y x  x 2)
=> (print x y)
2 1

You can perform parallel assignments or unpack the source value with square brackets and unpack-iterable:

=> (setv duo ["tim" "eric"])
=> (setv [guy1 guy2] duo)
=> (print guy1 guy2)
tim eric

=> (setv [letter1 letter2 #* others] "abcdefg")
=> (print letter1 letter2 others)
a b ['c', 'd', 'e', 'f', 'g']
(setx #* args)

Whereas setv creates an assignment statement, setx creates an assignment expression (see PEP 572). It requires Python 3.8 or later. Only one target–value pair is allowed, and the target must be a bare symbol, but the setx form returns the assigned value instead of None.

Examples

=> (when (> (setx x (+ 1 2)) 0)
...  (print x "is greater than 0"))
3 is greater than 0
(defclass class-name super-classes #* body)

New classes are declared with defclass. It can take optional parameters in the following order: a list defining (a) possible super class(es) and a string (docstring).

Examples

=> (defclass class-name [super-class-1 super-class-2]
...   "docstring"
...
...   (setv attribute1 value1)
...   (setv attribute2 value2)
...
...   (defn method [self] (print "hello!")))

Both values and functions can be bound on the new class as shown by the example below:

=> (defclass Cat []
...  (setv age None)
...  (setv colour "white")
...
...  (defn speak [self] (print "Meow")))

=> (setv spot (Cat))
=> (setv spot.colour "Black")
'Black'
=> (.speak spot)
Meow
(del object)

New in version 0.9.12.

del removes an object from the current namespace.

Examples

=> (setv foo 42)
=> (del foo)
=> foo
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'foo' is not defined

del can also remove objects from mappings, lists, and more.

=> (setv test (list (range 10)))
=> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
=> (del (cut test 2 4)) ;; remove items from 2 to 4 excluded
=> test
[0, 1, 4, 5, 6, 7, 8, 9]
=> (setv dic {"foo" "bar"})
=> dic
{"foo": "bar"}
=> (del (get dic "foo"))
=> dic
{}
(nonlocal object)

New in version 0.11.1.

nonlocal can be used to mark a symbol as not local to the current scope. The parameters are the names of symbols to mark as nonlocal. This is necessary to modify variables through nested fn scopes:

Examples

(defn some-function []
  (setv x 0)
  (register-some-callback
    (fn [stuff]
      (nonlocal x)
      (setv x stuff))))

Without the call to (nonlocal x), the inner function would redefine x to stuff inside its local scope instead of overwriting the x in the outer function.

See PEP3104 for further information.

(py string)

py parses the given Python code at compile-time and inserts the result into the generated abstract syntax tree. Thus, you can mix Python code into a Hy program. Only a Python expression is allowed, not statements; use pys if you want to use Python statements. The value of the expression is returned from the py form.

(print "A result from Python:" (py "'hello' + 'world'"))

The code must be given as a single string literal, but you can still use macros, hy.eval, and related tools to construct the py form. If having to backslash-escape internal double quotes is getting you down, try a bracket string. If you want to evaluate some Python code that’s only defined at run-time, try the standard Python function eval().

Python code need not syntactically round-trip if you use hy2py on a Hy program that uses py or pys. For example, comments will be removed.

(pys string)

As py, but the code can consist of zero or more statements, including compound statements such as for and def. pys always returns None. Also, the code string is dedented with textwrap.dedent() before parsing, which allows you to intend the code to match the surrounding Hy code, but significant leading whitespace in embedded string literals will be removed.

(pys "myvar = 5")
(print "myvar is" myvar)
(quasiquote form)

quasiquote allows you to quote a form, but also selectively evaluate expressions. Expressions inside a quasiquote can be selectively evaluated using unquote (~). The evaluated form can also be spliced using unquote-splice (~@). Quasiquote can be also written using the backquote (`) symbol.

Examples

;; let `qux' be a variable with value (bar baz)
`(foo ~qux)
; equivalent to '(foo (bar baz))
`(foo ~@qux)
; equivalent to '(foo bar baz)
(quote form)

quote returns the form passed to it without evaluating it. quote can alternatively be written using the apostrophe (') symbol.

Examples

=> (setv x '(print "Hello World"))
=> x  ; variable x is set to unevaluated expression
hy.models.Expression([
  hy.models.Symbol('print'),
  hy.models.String('Hello World')])
=> (hy.eval x)
Hello World
(require #* args)

require is used to import macros from one or more given modules. It allows parameters in all the same formats as import. The require form itself produces no code in the final program: its effect is purely at compile-time, for the benefit of macro expansion. Specifically, require imports each named module and then makes each requested macro available in the current module.

The following are all equivalent ways to call a macro named foo in the module mymodule:

Examples

(require mymodule)
(mymodule.foo 1)

(require [mymodule :as M])
(M.foo 1)

(require [mymodule [foo]])
(foo 1)

(require [mymodule [*]])
(foo 1)

(require [mymodule [foo :as bar]])
(bar 1)

Macros that call macros

One aspect of require that may be surprising is what happens when one macro’s expansion calls another macro. Suppose mymodule.hy looks like this:

(defmacro repexpr [n expr]
  ; Evaluate the expression n times
  ; and collect the results in a list.
  `(list (map (fn [_] ~expr) (range ~n))))

(defmacro foo [n]
  `(repexpr ~n (input "Gimme some input: ")))

And then, in your main program, you write:

(require [mymodule [foo]])

(print (mymodule.foo 3))

Running this raises NameError: name 'repexpr' is not defined, even though writing (print (foo 3)) in mymodule works fine. The trouble is that your main program doesn’t have the macro repexpr available, since it wasn’t imported (and imported under exactly that name, as opposed to a qualified name). You could do (require [mymodule [*]]) or (require [mymodule [foo repexpr]]), but a less error-prone approach is to change the definition of foo to require whatever sub-macros it needs:

(defmacro foo [n]
  `(do
    (require mymodule)
    (mymodule.repexpr ~n (input "Gimme some input: "))))

It’s wise to use (require mymodule) here rather than (require [mymodule [repexpr]]) to avoid accidentally shadowing a function named repexpr in the main program.

Note

Qualified macro names

Note that in the current implementation, there’s a trick in qualified macro names, like mymodule.foo and M.foo in the above example. These names aren’t actually attributes of module objects; they’re just identifiers with periods in them. In fact, mymodule and M aren’t defined by these require forms, even at compile-time. None of this will hurt you unless try to do introspection of the current module’s set of defined macros, which isn’t really supported anyway.

(return object)

return compiles to a return statement. It exits the current function, returning its argument if provided with one or None if not.

Examples

=> (defn f [x] (for [n (range 10)] (when (> n x) (return n))))
=> (f 3.9)
4

Note that in Hy, return is necessary much less often than in Python, since the last form of a function is returned automatically. Hence, an explicit return is only necessary to exit a function early.

=> (defn f [x] (setv y 10) (+ x y))
=> (f 4)
14

To get Python’s behavior of returning None when execution reaches the end of a function, put None there yourself.

=> (defn f [x] (setv y 10) (+ x y) None)
=> (print (f 4))
None
(cut coll [start None] [stop None] [step None)

cut can be used to take a subset of a list and create a new list from it. The form takes at least one parameter specifying the list to cut. Two optional parameters can be used to give the start and end position of the subset. If they are not supplied, the default value of None will be used instead. The third optional parameter is used to control step between the elements.

cut follows the same rules as its Python counterpart. Negative indices are counted starting from the end of the list. Some example usage:

Examples

=> (setv collection (range 10))
=> (cut collection)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

=> (cut collection 5)
[5, 6, 7, 8, 9]

=> (cut collection 2 8)
[2, 3, 4, 5, 6, 7]

=> (cut collection 2 8 2)
[2, 4, 6]

=> (cut collection -4 -2)
[6, 7]
(raise [exception None])

The raise form can be used to raise an Exception at runtime. Example usage:

Examples

(raise)
; re-rase the last exception

(raise IOError)
; raise an IOError

(raise (IOError "foobar"))
; raise an IOError("foobar")

raise can accept a single argument (an Exception class or instance) or no arguments to re-raise the last Exception.

(try #* body)

The try form is used to catch exceptions (except) and run cleanup actions (finally).

Examples

(try
  (error-prone-function)
  (another-error-prone-function)
  (except [ZeroDivisionError]
    (print "Division by zero"))
  (except [[IndexError KeyboardInterrupt]]
    (print "Index error or Ctrl-C"))
  (except [e ValueError]
    (print "ValueError:" (repr e)))
  (except [e [TabError PermissionError ReferenceError]]
    (print "Some sort of error:" (repr e)))
  (else
    (print "No errors"))
  (finally
    (print "All done")))

The first argument of try is its body, which can contain one or more forms. Then comes any number of except clauses, then optionally an else clause, then optionally a finally clause. If an exception is raised with a matching except clause during the execution of the body, that except clause will be executed. If no exceptions are raised, the else clause is executed. The finally clause will be executed last regardless of whether an exception was raised.

The return value of try is the last form of the except clause that was run, or the last form of else if no exception was raised, or the try body if there is no else clause.

unpack-iterable/unpack-mapping

(Also known as the splat operator, star operator, argument expansion, argument explosion, argument gathering, and varargs, among others…)

unpack-iterable and unpack-mapping allow an iterable or mapping object (respectively) to provide positional or keywords arguments (respectively) to a function.

=> (defn f [a b c d] [a b c d])
=> (f (unpack-iterable [1 2]) (unpack-mapping {"c" 3 "d" 4}))
[1, 2, 3, 4]

unpack-iterable is usually written with the shorthand #*, and unpack-mapping with #**.

=> (f #* [1 2] #** {"c" 3 "d" 4})
[1, 2, 3, 4]

Unpacking is allowed in a variety of contexts, and you can unpack more than once in one expression (PEP 3132, PEP 448).

=> (setv [a #* b c] [1 2 3 4 5])
=> [a b c]
[1, [2, 3, 4], 5]
=> [#* [1 2] #* [3 4]]
[1, 2, 3, 4]
=> {#** {1 2} #** {3 4}}
{1: 2, 3: 4}
=> (f #* [1] #* [2] #** {"c" 3} #** {"d" 4})
[1, 2, 3, 4]
(unquote symbol)

Within a quasiquoted form, unquote forces evaluation of a symbol. unquote is aliased to the tilde (~) symbol.

=> (setv nickname "Cuddles")
=> (quasiquote (= nickname (unquote nickname)))
hy.models.Expression([
  hy.models.Symbol('='),
  hy.models.Symbol('nickname'),
  'Cuddles'])
=> `(= nickname ~nickname)
hy.models.Expression([
  hy.models.Symbol('='),
  hy.models.Symbol('nickname'),
  'Cuddles'])
(unquote-splice symbol)

unquote-splice forces the evaluation of a symbol within a quasiquoted form, much like unquote. unquote-splice can be used when the symbol being unquoted contains an iterable value, as it “splices” that iterable into the quasiquoted form. unquote-splice can also be used when the value evaluates to a false value such as None, False, or 0, in which case the value is treated as an empty list and thus does not splice anything into the form. unquote-splice is aliased to the ~@ syntax.

=> (setv nums [1 2 3 4])
=> (quasiquote (+ (unquote-splice nums)))
hy.models.Expression([
  hy.models.Symbol('+'),
  1,
  2,
  3,
  4])
=> `(+ ~@nums)
hy.models.Expression([
  hy.models.Symbol('+'),
  1,
  2,
  3,
  4])
=> `[1 2 ~@(if (neg? (first nums)) nums)]
hy.models.List([
  hy.models.Integer(1),
  hy.models.Integer(2)])

Here, the last example evaluates to ('+' 1 2), since the condition (< (nth nums 0) 0) is False, which makes this if expression evaluate to None, because the if expression here does not have an else clause. unquote-splice then evaluates this as an empty value, leaving no effects on the list it is enclosed in, therefore resulting in ('+' 1 2).

(while condition #* body)

while compiles to a while statement. It is used to execute a set of forms as long as a condition is met. The first argument to while is the condition, and any remaining forms constitute the body. The following example will output “Hello world!” to the screen indefinitely:

(while True (print "Hello world!"))

The last form of a while loop can be an else clause, which is executed after the loop terminates, unless it exited abnormally (e.g., with break). So,

(setv x 2)
(while x
   (print "In body")
   (-= x 1)
   (else
     (print "In else")))

prints

In body
In body
In else

If you put a break or continue form in the condition of a while loop, it will apply to the very same loop rather than an outer loop, even if execution is yet to ever reach the loop body. (Hy compiles a while loop with statements in its condition by rewriting it so that the condition is actually in the body.) So,

(for [x [1]]
   (print "In outer loop")
   (while
     (do
       (print "In condition")
       (break)
       (print "This won't print.")
       True)
     (print "This won't print, either."))
   (print "At end of outer loop"))

prints

In outer loop
In condition
At end of outer loop
(with #* args)

Wrap execution of body within a context manager given as bracket args. with is used to wrap the execution of a block within a context manager. The context manager can then set up the local system and tear it down in a controlled manner. The archetypical example of using with is when processing files. If only a single expression is supplied, or the argument is _, then no variable is bound to the expression, as shown below.

Examples:
=> (with [arg (expr)] block)
=> (with [(expr)] block)
=> (with [arg1 (expr1)  _ (expr2)  arg3 (expr3)] block)

The following example will open the NEWS file and print its content to the screen. The file is automatically closed after it has been processed:

=> (with [f (open \"NEWS\")] (print (.read f)))

with returns the value of its last form, unless it suppresses an exception (because the context manager’s __exit__ method returned true), in which case it returns None. So, the previous example could also be written:

=> (print (with [f (open \"NEWS\")] (.read f)))
(with/a #* args)

Wrap execution of body within a context manager given as bracket args. with/a behaves like with, but is used to wrap the execution of a block within an asynchronous context manager. The context manager can then set up the local system and tear it down in a controlled manner asynchronously. Examples:

::

=> (with/a [arg (expr)] block) => (with/a [(expr)] block) => (with/a [_ (expr) arg (expr) _ (expr)] block)

Note

with/a returns the value of its last form, unless it suppresses an exception (because the context manager’s __aexit__ method returned true), in which case it returns None.

(with-decorator #* args)

with-decorator is used to wrap a function with another. The function performing the decoration should accept a single value: the function being decorated, and return a new function. with-decorator takes a minimum of two parameters: the function performing decoration and the function being decorated. More than one decorator function can be applied; they will be applied in order from outermost to innermost, ie. the first decorator will be the outermost one, and so on. Decorators with arguments are called just like a function call.

(with-decorator decorator-fun
   (defn some-function [] ...)

(with-decorator decorator1 decorator2 ...
   (defn some-function [] ...)

(with-decorator (decorator arg) ..
   (defn some-function [] ...)

In the following example, inc-decorator is used to decorate the function addition with a function that takes two parameters and calls the decorated function with values that are incremented by 1. When the decorated addition is called with values 1 and 1, the end result will be 4 (1+1 + 1+1).

=> (defn inc-decorator [func]
...  (fn [value-1 value-2] (func (+ value-1 1) (+ value-2 1))))
=> (defn inc2-decorator [func]
...  (fn [value-1 value-2] (func (+ value-1 2) (+ value-2 2))))

=> (with-decorator inc-decorator (defn addition [a b] (+ a b)))
=> (addition 1 1)
4
=> (with-decorator inc2-decorator inc-decorator
...  (defn addition [a b] (+ a b)))
=> (addition 1 1)
8
(yield object)

yield is used to create a generator object that returns one or more values. The generator is iterable and therefore can be used in loops, list comprehensions and other similar constructs.

The function random-numbers shows how generators can be used to generate infinite series without consuming infinite amount of memory.

Examples

=> (defn multiply [bases coefficients]
...  (for [(, base coefficient) (zip bases coefficients)]
...   (yield (* base coefficient))))

=> (multiply (range 5) (range 5))
<generator object multiply at 0x978d8ec>

=> (list (multiply (range 10) (range 10)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

=> (import random)
=> (defn random-numbers [low high]
...  (while True (yield (.randint random low high))))
=> (list (take 15 (random-numbers 1 50)))
[7, 41, 6, 22, 32, 17, 5, 38, 18, 38, 17, 14, 23, 23, 19]
(yield-from object)

New in version 0.9.13.

yield-from is used to call a subgenerator. This is useful if you want your coroutine to be able to delegate its processes to another coroutine, say, if using something fancy like asyncio.

Core

class *map

alias of itertools.starmap

class accumulate

accumulate(iterable[, func]) –> accumulate object

Return series of accumulated sums (or other binary function results).

(butlast coll)

Returns an iterator of all but the last item in coll.

Examples

=> (list (butlast (range 10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
=> (list (butlast [1]))
[]
=> (list (butlast []))
[]
=> (list (take 5 (butlast (count 10))))
[10, 11, 12, 13, 14]
(calling-module [n 1])

Get the module calling, if available.

As a fallback, this will import a module using the calling frame’s globals value of __name__.

Parameters

n (int, optional) – The number of levels up the stack from this function call. The default is one level up.

Returns

out – The module at stack level n + 1 or None.

Return type

types.ModuleType

(calling-module-name [n 1])

Get the name of the module calling n levels up the stack from the calling-module-name function call (by default, one level up)

class chain

chain(*iterables) –> chain object

Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.

(from-iterable)

chain.from_iterable(iterable) –> chain object

Alternate chain() constructor taking a single iterable argument that evaluates lazily.

(coll? coll)

Returns True if x is iterable and not a string.

New in version 0.10.0.

Examples

=> (coll? [1 2 3 4])
True
=> (coll? {"a" 1 "b" 2})
True
=> (coll? "abc")
False
class combinations

combinations(iterable, r) –> combinations object

Return successive r-length combinations of elements in the iterable.

combinations(range(4), 3) –> (0,1,2), (0,1,3), (0,2,3), (1,2,3)

(comp #* fs)

Return the function from composing the given functions fs.

Compose zero or more functions into a new function. The new function will chain the given functions together, so ((comp g f) x) is equivalent to (g (f x)). Called without arguments, comp returns identity.

Examples

=> (setv example (comp str +))
=> (example 1 2 3)
"6"
=> (setv simple (comp))
=> (simple "hello")
"hello"
(complement f)

Returns a new function that returns the logically inverted result of f.

New in version 0.12.0.

Returns a new function that returns the same thing as f, but logically inverted. So, ((complement f) x) is equivalent to (not (f x)).

Examples

=> (setv inverse (complement identity))
=> (inverse True)
False
=> (inverse 1)
False
=> (inverse False)
True
class compress

compress(data, selectors) –> iterator over selected data

Return data elements corresponding to true selector elements. Forms a shorter iterator from selected data elements using the selectors to choose the data elements.

(constantly value)

Create a new function that always returns value regardless of its input.

New in version 0.12.0.

Create a new function that always returns the given value, regardless of the arguments given to it.

Examples

=> (setv answer (constantly 42))
=> (answer)
42
=> (answer 1 2 3)
42
=> (answer 1 :foo 2)
42
class count

count(start=0, step=1) –> count object

Return a count object whose .__next__() method returns consecutive values. Equivalent to:

def count(firstval=0, step=1):

x = firstval while 1:

yield x x += step

class cycle

cycle(iterable) –> cycle object

Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.

(dec n)

Decrement n by 1.

Returns one less than x. Equivalent to (- x 1). Raises TypeError if (not (numeric? x)).

Examples

=> (dec 3)
2
=> (dec 0)
-1
=> (dec 12.3)
11.3
(disassemble tree [codegen False])

Return the python AST for a quoted Hy tree as a string.

If the second argument codegen is true, generate python code instead.

New in version 0.10.0.

Dump the Python AST for given Hy tree to standard output. If codegen is True, the function prints Python code instead.

Examples

=> (disassemble '(print "Hello World!"))
Module(
 body=[
     Expr(value=Call(func=Name(id='print'), args=[Str(s='Hello World!')], keywords=[], starargs=None, kwargs=None))])
=> (disassemble '(print "Hello World!") True)
print('Hello World!')
(distinct coll)

Return a generator from the original collection coll with no duplicates.

Examples

=> (list (distinct [ 1 2 3 4 3 5 2 ]))
[1, 2, 3, 4, 5]
=> (list (distinct []))
[]
=> (list (distinct (iter [ 1 2 3 4 3 5 2 ])))
[1, 2, 3, 4, 5]
(drop count coll)

Drop count elements from coll and yield back the rest.

Returns an iterator, skipping the first n members of coll. Raises ValueError if n is negative.

Examples

=> (list (drop 2 [1 2 3 4 5]))
[3, 4, 5]
=> (list (drop 4 [1 2 3 4 5]))
[5]
=> (list (drop 0 [1 2 3 4 5]))
[1, 2, 3, 4, 5]
=> (list (drop 6 [1 2 3 4 5]))
[]
(drop-last n coll)

Return a sequence of all but the last n elements in coll.

Returns an iterator of all but the last n items in coll. Raises ValueError if n is negative.

Examples

=> (list (drop-last 5 (range 10 20)))
[10, 11, 12, 13, 14]
=> (list (drop-last 0 (range 5)))
[0, 1, 2, 3, 4]
=> (list (drop-last 100 (range 100)))
[]
=> (list (take 5 (drop-last 100 (count 10))))
[10, 11, 12, 13, 14]
class drop-while

alias of itertools.dropwhile

(empty? coll)

Check if coll is empty.

Returns True if coll is empty. Equivalent to (= 0 (len coll)).

Examples

=> (empty? [])
True
=> (empty?
(even? n)

Check if n is an even number.

Returns True if x is even. Raises TypeError if (not (numeric? x)).

Examples

=> (even? 2)
True
=> (even? 13)
False
=> (even? 0)
True
(every? pred coll)

Check if pred is true applied to every x in coll.

New in version 0.10.0.

Returns True if (pred x) is logical true for every x in coll, otherwise False. Return True if coll is empty.

Examples

=> (every? even? [2 4 6])
True
=> (every? even? [1 3 5])
False
=> (every? even? [2 4 5])
False
=> (every? even? [])
True
(first coll)

Return first item from coll.

It is implemented as (next (iter coll) None), so it works with any iterable, and if given an empty iterable, it will return None instead of raising an exception.

Examples

=> (first (range 10))
0
=> (first (repeat 10))
10
=> (first [])
None
(flatten coll)

Return a single flat list expanding all members of coll.

New in version 0.9.12.

Returns a single list of all the items in coll, by flattening all contained lists and/or tuples.

Examples

=> (flatten [1 2 [3 4] 5])
[1, 2, 3, 4, 5]
=> (flatten ["foo" (, 1 2) [1 [2 3] 4] "bar"])
['foo', 1, 2, 1, 2, 3, 4, 'bar']
(float? x)

Returns True if x is a float.

Examples

=> (float? 3.2)
True
=> (float? -2)
False
class (fraction cls  [numerator 0] denominator *  [_normalize True])

alias of fractions.Fraction

classmethod (from-decimal cls dec)

Converts a finite Decimal instance to a rational number, exactly.

classmethod (from-float cls f)

Converts a finite float to a rational number, exactly.

Beware that Fraction.from_float(0.3) != Fraction(3, 10).

(limit-denominator [max-denominator 1000000])

Closest Fraction to self with denominator at most max_denominator.

>>> Fraction('3.141592653589793').limit_denominator(10)
Fraction(22, 7)
>>> Fraction('3.141592653589793').limit_denominator(100)
Fraction(311, 99)
>>> Fraction(4321, 8765).limit_denominator(10000)
Fraction(4321, 8765)
(gensym [g G])

Generate a unique symbol for use in macros without accidental name clashes.

New in version 0.9.12.

Examples

=> (gensym)
hy.models.Symbol('_G￿1')
=> (gensym "x")
hy.models.Symbol('_x￿2')
class group-by

alias of itertools.groupby

(identity x)

Return x.

Examples

=> (identity 4)
4
=> (list (map identity [1 2 3 4]))
[1 2 3 4]
(inc n)

Increment n by 1.

Returns one more than x. Equivalent to (+ x 1). Raises TypeError if (not (numeric? x)).

Examples

=> (inc 3)
4
=> (inc 0)
1
=> (inc 12.3)
13.3
(instance? klass x)

Perform isinstance with reversed arguments.

Returns True if x is an instance of class.

Examples

=> (instance? float 1.0)
True
=> (instance? int 7)
True
=> (instance? str (str "foo"))
True
=> (defclass TestClass [object])
=> (setv inst (TestClass))
=> (instance? TestClass inst)
True
(integer-char? x)

Check if char x parses as an integer.

(integer? x)

Check if x is an integer.

Examples

=> (integer? 3)
True
=> (integer? -2.4)
False
(interleave #* seqs)

Return an iterable of the first item in each of seqs, then the second etc.

New in version 0.10.1.

Examples

=> (list (interleave (range 5) (range 100 105)))
[0, 100, 1, 101, 2, 102, 3, 103, 4, 104]
=> (list (interleave (range 1000000) "abc"))
[0, 'a', 1, 'b', 2, 'c']
(interpose item seq)

Return an iterable of the elements of seq separated by item.

New in version 0.10.1.

Examples

=> (list (interpose "!" "abcd"))
['a', '!', 'b', '!', 'c', '!', 'd']
=> (list (interpose -1 (range 5)))
[0, -1, 1, -1, 2, -1, 3, -1, 4]
class islice

islice(iterable, stop) –> islice object islice(iterable, start, stop[, step]) –> islice object

Return an iterator whose next() method returns selected values from an iterable. If start is specified, will skip all preceding elements; otherwise, start defaults to zero. Step defaults to one. If specified as another value, step determines how many values are skipped between successive calls. Works like a slice() on a list but returns an iterator.

(iterable? x)

Check if x is an iterable.

Returns True if x is iterable. Iterable objects return a new iterator when (iter x) is called. Contrast with iterator?.

Examples

=> ;; works for strings
=> (iterable? (str "abcde"))
True
=> ;; works for lists
=> (iterable? [1 2 3 4 5])
True
=> ;; works for tuples
=> (iterable? (, 1 2 3))
True
=> ;; works for dicts
=> (iterable? {:a 1 :b 2 :c 3})
True
=> ;; works for iterators/generators
=> (iterable? (repeat 3))
True
(iterate f x)

Returns an iterator repeatedly applying f to seed x.. x, f(x), f(f(x))…

Examples

=> (list (take 5 (iterate inc 5)))
[5, 6, 7, 8, 9]
=> (list (take 5 (iterate (fn [x] (* x x)) 5)))
[5, 25, 625, 390625, 152587890625]
(iterator? x)

Check if x is an iterator.

Returns True if x is an iterator. Iterators are objects that return themselves as an iterator when (iter x) is called. Contrast with iterable?.

Examples

=> ;; doesn't work for a list
=> (iterator? [1 2 3 4 5])
False
=> ;; but we can get an iter from the list
=> (iterator? (iter [1 2 3 4 5]))
True
=> ;; doesn't work for dict
=> (iterator? {:a 1 :b 2 :c 3})
False
=> ;; create an iterator from the dict
=> (iterator? (iter {:a 1 :b 2 :c 3}))
True
(juxt f #* fs)

Return a function applying each fs to args, collecting results in a list.

New in version 0.12.0.

Return a function that applies each of the supplied functions to a single set of arguments and collects the results into a list.

Examples

=> ((juxt min max sum) (range 1 101))
[1, 100, 5050]
=> (dict (map (juxt identity ord) "abcdef"))
{'f': 102, 'd': 100, 'b': 98, 'e': 101, 'c': 99, 'a': 97}
=> ((juxt + - * /) 24 3)
[27, 21, 72, 8.0]
(keyword value)

Create a keyword from value.

Strings numbers and even objects with the __name__ magic will work.

Examples

=> (keyword "foo")
hy.models.Keyword('foo')
=> (keyword 1)
hy.models.Keyword('foo')
(keyword? k)

Check whether k is a keyword.

New in version 0.10.1.

Check whether foo is a keyword.

Examples

=> (keyword? :foo)
True
=> (setv foo 1)
=> (keyword? foo)
False
(last coll)

Return last item from coll.

New in version 0.11.0.

Examples

=> (last [2 4 6])
6
(list? x)

Check if x is a list

Examples

=> (list? '(inc 41))
True
=> (list? '42)
False
(macroexpand form)

Return the full macro expansion of form.

New in version 0.10.0.

Examples

=> (macroexpand '(-> (a b) (x y)))
hy.models.Expression([
  hy.models.Symbol('x'),
  hy.models.Expression([
    hy.models.Symbol('a'),
    hy.models.Symbol('b')]),
  hy.models.Symbol('y')])
=> (macroexpand '(-> (a b) (-> (c d) (e f))))
hy.models.Expression([
  hy.models.Symbol('e'),
  hy.models.Expression([
    hy.models.Symbol('c'),
    hy.models.Expression([
      hy.models.Symbol('a'),
      hy.models.Symbol('b')]),
    hy.models.Symbol('d')]),
  hy.models.Symbol('f')])
(macroexpand-1 form)

Return the single step macro expansion of form.

New in version 0.10.0.

Examples

=> (macroexpand-1 '(-> (a b) (-> (c d) (e f))))
hy.models.Expression([
  hy.models.Symbol('_>'),
  hy.models.Expression([
    hy.models.Symbol('a'),
    hy.models.Symbol('b')]),
  hy.models.Expression([
    hy.models.Symbol('c'),
    hy.models.Symbol('d')]),
  hy.models.Expression([
    hy.models.Symbol('e'),
    hy.models.Symbol('f')])])
(mangle s)

Stringify the argument and convert it to a valid Python identifier according to Hy’s mangling rules.

Examples

=> (mangle 'foo-bar)
"foo_bar"

=> (mangle 'foo-bar?)
"is_foo_bar"

=> (mangle '*)
"hyx_XasteriskX"

=> (mangle '_foo/a?)
"_hyx_is_fooXsolidusXa"

=> (mangle '-->)
"hyx_XhyphenHminusX_XgreaterHthan_signX"

=> (mangle '<--)
"hyx_XlessHthan_signX__"
(merge-with f #* maps)

Return the map of maps joined onto the first via the function f.

New in version 0.10.1.

Returns a map that consist of the rest of the maps joined onto first. If a key occurs in more than one map, the mapping(s) from the latter (left-to-right) will be combined with the mapping in the result by calling (f val-in-result val-in-latter).

Examples

=> (merge-with + {"a" 10 "b" 20} {"a" 1 "c" 30})
{u'a': 11L, u'c': 30L, u'b': 20L}
class multicombinations

alias of itertools.combinations_with_replacement

(neg? n)

Check if n is < 0.

Returns True if x is less than zero. Raises TypeError if (not (numeric? x)).

Examples

=> (neg? -2)
True
=> (neg? 3)
False
=> (neg? 0)
False
(none? x)

Check if x is None

Examples

=> (none? None)
True
=> (none? 0)
False
=> (setv x None)
=> (none? x)
True
=> ;; list.append always returns None
=> (none? (.append [1 2 3] 4))
True
(nth coll n default)

Return n`th item in `coll or None (specify default) if out of bounds.

Returns the n-th item in a collection, counting from 0. Return the default value, None, if out of bounds (unless specified otherwise). Raises ValueError if n is negative.

Examples

=> (nth [1 2 4 7] 1)
2
=> (nth [1 2 4 7] 3)
7
=> (none? (nth [1 2 4 7] 5))
True
=> (nth [1 2 4 7] 5 "default")
'default'
=> (nth (take 3 (drop 2 [1 2 3 4 5 6])) 2))
5
=> (nth [1 2 4 7] -1)
Traceback (most recent call last):
...
ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.
(numeric? x)

Check if x is an instance of numbers.Number.

Examples

=> (numeric? -2)
True
=> (numeric? 3.2)
True
=> (numeric? "foo")
False
(odd? ^int n)

Check if n is an odd number.

Returns True if x is odd. Raises TypeError if (not (numeric? x)).

Examples

=> (odd? 13)
True
=> (odd? 2)
False
=> (odd? 0)
False
(parse-args spec args #** parser-args)

Return arguments namespace parsed from args or sys.argv with argparse.ArgumentParser.parse_args() according to spec.

spec should be a list of arguments which will be passed to repeated calls to argparse.ArgumentParser.add_argument(). parser-args may be a list of keyword arguments to pass to the argparse.ArgumentParser constructor.

Examples

=> (parse-args [["strings" :nargs "+" :help "Strings"]
...             ["-n" "--numbers" :action "append" :type int :help "Numbers"]]
...            ["a" "b" "-n" "1" "-n" "2"]
...            :description "Parse strings and numbers from args")
Namespace(numbers=[1, 2], strings=['a', 'b'])
(partition coll  [n 2] step  [fillvalue <object object at 0x7fdce8ec7050>])

Usage: (partition coll [n] [step] [fillvalue])

Chunks coll into n-tuples (pairs by default).

Examples

=> (list (partition (range 10)))  ; n=2
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

The step defaults to n, but can be more to skip elements, or less for a sliding window with overlap:

=> (list (partition (range 10) 2 3))
[(0, 1), (3, 4), (6, 7)]
=> (list (partition (range 5) 2 1))
[(0, 1), (1, 2), (2, 3), (3, 4)]

The remainder, if any, is not included unless a fillvalue is specified:

=> (list (partition (range 10) 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
=> (list (partition (range 10) 3 :fillvalue "x"))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 'x', 'x')]
class permutations

permutations(iterable[, r]) –> permutations object

Return successive r-length permutations of elements in the iterable.

permutations(range(3), 2) –> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)

(pos? n)

Check if n is > 0.

Returns True if x is greater than zero. Raises TypeError if (not (numeric? x)).

Examples

=> (pos? 3)
True
=> (pos? -2)
False
=> (pos? 0)
False
class product

product(*iterables, repeat=1) –> product object

Cartesian product of input iterables. Equivalent to nested for-loops.

For example, product(A, B) returns the same as: ((x,y) for x in A for y in B). The leftmost iterators are in the outermost for-loop, so the output tuples cycle in a manner similar to an odometer (with the rightmost element changing on every iteration).

To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).

product(‘ab’, range(3)) –> (‘a’,0) (‘a’,1) (‘a’,2) (‘b’,0) (‘b’,1) (‘b’,2) product((0,1), (0,1), (0,1)) –> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) …

(read [from-file <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>]  [eof ])

Read from input and returns a tokenized string.

Can take a given input buffer to read from, and a single byte as EOF (defaults to an empty string).

Reads the next Hy expression from from-file (defaulting to sys.stdin), and can take a single byte as EOF (defaults to an empty string). Raises EOFError if from-file ends before a complete expression can be parsed.

Examples

=> (read)
(+ 2 2)
hy.models.Expression([
  hy.models.Symbol('+'),
  hy.models.Integer(2),
  hy.models.Integer(2)])
=> (hy.eval (read))
(+ 2 2)
4
=> (import io)
=> (setv buffer (io.StringIO "(+ 2 2)\n(- 2 1)"))
=> (hy.eval (read :from-file buffer))
4
=> (hy.eval (read :from-file buffer))
1
=> (with [f (open "example.hy" "w")]
...  (.write f "(print 'hello)\n(print "hyfriends!")"))
35
=> (with [f (open "example.hy")]
...  (try (while True
...         (setv exp (read f))
...         (print "OHY" exp)
...         (hy.eval exp))
...       (except [e EOFError]
...         (print "EOF!"))))
OHY hy.models.Expression([
  hy.models.Symbol('print'),
  hy.models.Expression([
    hy.models.Symbol('quote'),
    hy.models.Symbol('hello')])])
hello
OHY hy.models.Expression([
  hy.models.Symbol('print'),
  hy.models.String('hyfriends!')])
hyfriends!
EOF!
(read-str input)

This is essentially a wrapper around read which reads expressions from a string

Examples

=> (read-str "(print 1)")
hy.models.Expression([
hy.models.Symbol('print'),
hy.models.Integer(1)]
=> (hy.eval (read-str "(print 1)"))
1
(reduce)

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

class remove

alias of itertools.filterfalse

class repeat

repeat(object [,times]) -> create an iterator which returns the object for the specified number of times. If not specified, returns the object endlessly.

(repeatedly func)

Yield result of running func repeatedly.

Examples

=> (import [random [randint]])
=> (list (take 5 (repeatedly (fn [] (randint 0 10)))))
[6, 2, 0, 6, 7]
(rest coll)

Get all the elements of coll, except the first.

rest takes the given collection and returns an iterable of all but the first element.

Examples

=> (list (rest (range 10)))
[1 2 3 4 5 6 7 8 9]

Given an empty collection, it returns an empty iterable:

=> (list (rest []))
[]
(second coll)

Return second item from coll.

Returns the second member of coll. Equivalent to (get coll 1).

Examples

=> (second [0 1 2])
1
(some pred coll)

Return the first logical true value of applying pred in coll, else None.

New in version 0.10.0.

Returns the first logically-true value of (pred x) for any x in coll, otherwise None. Return None if coll is empty.

Examples

=> (some even? [2 4 6])
True
=> (none? (some even? [1 3 5]))
True
=> (none? (some identity [0 "" []]))
True
=> (some identity [0 "non-empty-string" []])
'non-empty-string'
=> (none? (some even? []))
True
(string? x)

Check if x is a string.

Examples

=> (string? "foo")
True
=> (string? -2)
False
(symbol? s)

Check if s is a symbol.

Examples

=> (symbol? 'foo)
True
=> (symbol? '[a b c])
False
(take count coll)

Take count elements from coll.

Returns an iterator containing the first n members of coll. Raises ValueError if n is negative.

Examples

=> (list (take 3 [1 2 3 4 5]))
[1, 2, 3]
=> (list (take 4 (repeat "s")))
[u's', u's', u's', u's']
=> (list (take 0 (repeat "s")))
[]
(take-nth n coll)

Return every n`th member of `coll.

Examples

=> (list (take-nth 2 [1 2 3 4 5 6 7]))
[1, 3, 5, 7]
=> (list (take-nth 3 [1 2 3 4 5 6 7]))
[1, 4, 7]
=> (list (take-nth 4 [1 2 3 4 5 6 7]))
[1, 5]
=> (list (take-nth 10 [1 2 3 4 5 6 7]))
[1]
Raises

ValueError – for (not (pos? n)).

class take-while

alias of itertools.takewhile

(tee)

tee(iterable, n=2) –> tuple of n independent iterators.

(tuple? x)

Check if x is a tuple

Examples

=> (tuple? (, 42 44))
True
=> (tuple? [42 44])
False
(unmangle s)

Stringify the argument and try to convert it to a pretty unmangled form. This may not round-trip, because different Hy symbol names can mangle to the same Python identifier. See Hy’s mangling rules.

Examples

=> (unmangle 'foo_bar)
"foo-bar"

=> (unmangle 'is_foo_bar)
"foo-bar?"

=> (unmangle 'hyx_XasteriskX)
"*"

=> (unmangle '_hyx_is_fooXsolidusXa)
"_foo/a?"

=> (unmangle 'hyx_XhyphenHminusX_XgreaterHthan_signX)
"-->"

=> (unmangle 'hyx_XlessHthan_signX__)
"<--"

=> (unmangle '__dunder_name__)
"__dunder-name__"
(xor a b)

Perform exclusive or between a and b.

New in version 0.12.0.

xor performs the logical operation of exclusive OR. It takes two arguments. If exactly one argument is true, that argument is returned. If neither is true, the second argument is returned (which will necessarily be false). Otherwise, when both arguments are true, the value False is returned.

Examples

=> [(xor 0 0) (xor 0 1) (xor 1 0) (xor 1 1)]
[0 1 1 False]
(zero? n)

Check if n equals 0.

Examples

=> (zero? 3)
False
=> (zero? -2)
False
=> (zero? 0)
True
class zip-longest

alias of itertools.zip_longest

(calling-module [n 1])

Get the module calling, if available.

As a fallback, this will import a module using the calling frame’s globals value of __name__.

Parameters

n (int, optional) – The number of levels up the stack from this function call. The default is one level up.

Returns

out – The module at stack level n + 1 or None.

Return type

types.ModuleType

(mangle s)

Stringify the argument and convert it to a valid Python identifier according to Hy’s mangling rules.

Examples

=> (mangle 'foo-bar)
"foo_bar"

=> (mangle 'foo-bar?)
"is_foo_bar"

=> (mangle '*)
"hyx_XasteriskX"

=> (mangle '_foo/a?)
"_hyx_is_fooXsolidusXa"

=> (mangle '-->)
"hyx_XhyphenHminusX_XgreaterHthan_signX"

=> (mangle '<--)
"hyx_XlessHthan_signX__"
(unmangle s)

Stringify the argument and try to convert it to a pretty unmangled form. This may not round-trip, because different Hy symbol names can mangle to the same Python identifier. See Hy’s mangling rules.

Examples

=> (unmangle 'foo_bar)
"foo-bar"

=> (unmangle 'is_foo_bar)
"foo-bar?"

=> (unmangle 'hyx_XasteriskX)
"*"

=> (unmangle '_hyx_is_fooXsolidusXa)
"_foo/a?"

=> (unmangle 'hyx_XhyphenHminusX_XgreaterHthan_signX)
"-->"

=> (unmangle 'hyx_XlessHthan_signX__)
"<--"

=> (unmangle '__dunder_name__)
"__dunder-name__"
(read-str input)

This is essentially a wrapper around read which reads expressions from a string

Examples

=> (read-str "(print 1)")
hy.models.Expression([
hy.models.Symbol('print'),
hy.models.Integer(1)]
=> (hy.eval (read-str "(print 1)"))
1
(read [from-file <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>]  [eof ])

Read from input and returns a tokenized string.

Can take a given input buffer to read from, and a single byte as EOF (defaults to an empty string).

Reads the next Hy expression from from-file (defaulting to sys.stdin), and can take a single byte as EOF (defaults to an empty string). Raises EOFError if from-file ends before a complete expression can be parsed.

Examples

=> (read)
(+ 2 2)
hy.models.Expression([
  hy.models.Symbol('+'),
  hy.models.Integer(2),
  hy.models.Integer(2)])
=> (hy.eval (read))
(+ 2 2)
4
=> (import io)
=> (setv buffer (io.StringIO "(+ 2 2)\n(- 2 1)"))
=> (hy.eval (read :from-file buffer))
4
=> (hy.eval (read :from-file buffer))
1
=> (with [f (open "example.hy" "w")]
...  (.write f "(print 'hello)\n(print "hyfriends!")"))
35
=> (with [f (open "example.hy")]
...  (try (while True
...         (setv exp (read f))
...         (print "OHY" exp)
...         (hy.eval exp))
...       (except [e EOFError]
...         (print "EOF!"))))
OHY hy.models.Expression([
  hy.models.Symbol('print'),
  hy.models.Expression([
    hy.models.Symbol('quote'),
    hy.models.Symbol('hello')])])
hello
OHY hy.models.Expression([
  hy.models.Symbol('print'),
  hy.models.String('hyfriends!')])
hyfriends!
EOF!
(chain #* iters)

builtin alias for itertools.chain

(*map f iterable)

builtin alias for itertools.starmap

(compress data selectors)

builtin alias for itertools.compress

(drop-while predicate iterable)

Returns an iterator, skipping members of coll until pred is False.

=> (list (drop-while even? [2 4 7 8 9]))
[7, 8, 9]

=> (list (drop-while numeric? [1 2 3 None "a"])))
[None, u'a']

=> (list (drop-while pos? [2 4 7 8 9]))
[]

builtin alias for itertools.dropwhile

(filter pred coll)

Returns an iterator for all items in coll that pass the predicate pred.

See also remove.

=> (list (filter pos? [1 2 3 -4 5 -7]))
[1, 2, 3, 5]

=> (list (filter even? [1 2 3 -4 5 -7]))
[2, -4]
(group-by iterable [key None])

builtin alias for itertools.groupby

(islice iterable #* args)

Builtin alias for itertools.islice

(take-while predicate iterable)

Returns an iterator from coll as long as pred returns True.

=> (list (take-while pos? [ 1 2 3 -4 5]))
[1, 2, 3]

=> (list (take-while neg? [ -4 -3 1 2 5]))
[-4, -3]

=> (list (take-while neg? [ 1 2 3 -4 5]))
[]

Builtin alias for itertools.takewhile

(tee iterable [n 2])

Builtin alias for itertools.tee

(combinations iterable r)

Builtin alias for itertools.combinations

(multicombinations iterable r)

Builtin alias for itertools.combinations_with_replacement

(permutations iterable [r None])

Builtin alias for itertools.permutations

(product #* args * [repeat 1])

Builtin alias for itertools.product

(remove predicate iterable)

Returns an iterator from coll with elements that pass the predicate, pred, removed.

See also Filter Objects.

=> (list (remove odd? [1 2 3 4 5 6 7]))
[2, 4, 6]

=> (list (remove pos? [1 2 3 4 5 6 7]))
[]

=> (list (remove neg? [1 2 3 4 5 6 7]))
[1, 2, 3, 4, 5, 6, 7]

Builtin alias for itertools.filterfalse

(zip-longest #* iterables * fillvalue)

Builtin alias for itertools.zip_longest

(accumulate iterable [func None] * initial)

Builtin alias for itertools.accumulate

(count [start 0] [step 1])

Builtin alias for itertools.count

(cycle iterable)

Returns an infinite iterator of the members of coll.

=> (list (take 7 (cycle [1 2 3])))
[1, 2, 3, 1, 2, 3, 1]

=> (list (take 2 (cycle [1 2 3])))
[1, 2]

Builtin alias for itertools.cycle

(repeat object [times None])

Returns an iterator (infinite) of x.

=> (list (take 6 (repeat "s")))
[u's', u's', u's', u's', u's', u's']

Builtin alias for itertools.repeat

(reduce function iterable [initializer None])

Builtin alias for functools.reduce

class (Fraction cls  [numerator 0] denominator *  [_normalize True])

This class implements rational numbers.

In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must be Rational. The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.

Fractions can also be constructed from:

  • numeric strings similar to those accepted by the float constructor (for example, ‘-2.3’ or ‘1e10’)

  • strings of the form ‘123/456’

  • float and Decimal instances

  • other Rational instances (including integers)

classmethod (from-decimal cls dec)

Converts a finite Decimal instance to a rational number, exactly.

classmethod (from-float cls f)

Converts a finite float to a rational number, exactly.

Beware that Fraction.from_float(0.3) != Fraction(3, 10).

(limit-denominator [max-denominator 1000000])

Closest Fraction to self with denominator at most max_denominator.

>>> Fraction('3.141592653589793').limit_denominator(10)
Fraction(22, 7)
>>> Fraction('3.141592653589793').limit_denominator(100)
Fraction(311, 99)
>>> Fraction(4321, 8765).limit_denominator(10000)
Fraction(4321, 8765)
(!= a1 a2 #* a-rest)

Shadowed != operator perform neq comparison on a1 by a2, …, a-rest.

(% x y)

Shadowed % operator takes x modulo y.

(& a1 #* a-rest)

Shadowed & operator performs bitwise-and on a1 by each a-rest.

(* #* args)

Shadowed * operator multiplies args.

(** a1 a2 #* a-rest)

Shadowed ** operator takes a1 to the power of a2, …, a-rest.

(+ #* args)

Shadowed + operator adds args.

(- a1 #* a-rest)

Shadowed - operator subtracts each a-rest from a1.

(/ a1 #* a-rest)

Shadowed / operator divides a1 by each a-rest.

(// a1 a2 #* a-rest)

Shadowed // operator floor divides a1 by a2, …, a-rest.

(< a1 #* a-rest)

Shadowed < operator perform lt comparison on a1 by each a-rest.

(<< a1 a2 #* a-rest)

Shadowed << operator performs left-shift on a1 by a2, …, a-rest.

(<= a1 #* a-rest)

Shadowed <= operator perform le comparison on a1 by each a-rest.

(= a1 #* a-rest)

Shadowed = operator perform eq comparison on a1 by each a-rest.

(> a1 #* a-rest)

Shadowed > operator perform gt comparison on a1 by each a-rest.

(>= a1 #* a-rest)

Shadowed >= operator perform ge comparison on a1 by each a-rest.

(>> a1 a2 #* a-rest)

Shadowed >> operator performs right-shift on a1 by a2, …, a-rest.

(@ a1 #* a-rest)

Shadowed @ operator matrix multiples a1 by each a-rest.

(^ x y)

Shadowed ^ operator performs bitwise-xor on x and y.

(and #* args)

Shadowed and keyword perform and on args.

and is used in logical expressions. It takes at least two parameters. If all parameters evaluate to True, the last parameter is returned. In any other case, the first false value will be returned.

Note

and short-circuits and stops evaluating parameters as soon as the first false is encountered.

Examples

=> (and True False)
False
=> (and False (print "hello"))
False
=> (and True True)
True
=> (and True 1)
1
=> (and True [] False True)
[]
(get coll key1 #* keys)

Access item in coll indexed by key1, with optional keys nested-access.

get is used to access single elements in collections. get takes at least two parameters: the data structure and the index or key of the item. It will then return the corresponding value from the collection. If multiple index or key values are provided, they are used to access successive elements in a nested structure.

Note

get raises a KeyError if a dictionary is queried for a non-existing key.

Note

get raises an IndexError if a list or a tuple is queried for an index that is out of bounds.

Examples

=> (do
...   (setv animals {"dog" "bark" "cat" "meow"}
...         numbers (, "zero" "one" "two" "three")
...         nested [0 1 ["a" "b" "c"] 3 4])
...   (print (get animals "dog"))
...   (print (get numbers 2))
...   (print (get nested 2 1))
bark
two
b
(in a1 a2 #* a-rest)

Shadowed in keyword perform a1 in a2 in ….

(is a1 #* a-rest)

Shadowed is keyword perform is on a1 by each a-rest.

(not x)

Shadowed not keyword perform not on x.

not is used in logical expressions. It takes a single parameter and returns a reversed truth value. If True is given as a parameter, False will be returned, and vice-versa.

Examples

=> (not True)
False
=> (not False)
True
=> (not None)
True
(not-in a1 a2 #* a-rest)

Shadowed not in keyword perform a1 not in a2 not in….

(not? a1 a2 #* a-rest)

Shadowed is-not keyword perform is-not on a1 by a2, …, a-rest.

(or #* args)

Shadowed or keyword perform or on args.

or is used in logical expressions. It takes at least two parameters. It will return the first non-false parameter. If no such value exists, the last parameter will be returned.

Examples

=> (or True False)
True
=> (or False False)
False
=> (or False 1 True False)
1

Note

or short-circuits and stops evaluating parameters as soon as the first true value is encountered.

=> (or True (print "hello"))
True
(| #* args)

Shadowed | operator performs bitwise-or on a1 by each a-rest.

(~ x)

Shadowed ~ operator performs bitwise-negation on x.

(defmacro macro-name lambda-list #* body)

the defmacro macro defmacro is used to define macros. The general format is (defmacro name [parameters] expr).

The following example defines a macro that can be used to swap order of elements in code, allowing the user to write code in infix notation, where operator is in between the operands.

Examples

=> (defmacro infix [code]
...  (quasiquote (
...    (unquote (get code 1))
...    (unquote (get code 0))
...    (unquote (get code 2)))))
=> (infix (1 + 1))
2

The name of the macro can be given as a string literal instead of a symbol. If the name starts with #, the macro can be called on a single argument without parentheses; such a macro is called a tag macro.

=> (defmacro "#x2" [form]
...  `(do ~form ~form))
=> (setv foo 1)
=> #x2 (+= foo 1)
=> foo
3
(defn name #* args)

Define name as a function with args as the signature, annotations, and body.

defn is used to define functions. It requires two arguments: a name (given as a symbol) and a list of parameters (also given as symbols). Any remaining arguments constitute the body of the function:

(defn name [params] bodyform1 bodyform2...)

If there at least two body forms, and the first of them is a string literal, this string becomes the docstring of the function.

Parameters may be prefixed with the following special symbols. If you use more than one, they can only appear in the given order (so all positional only arguments must precede /, all positional or keyword arguments must precede a #* rest parameter or * kwonly delimiter and #** must be the last argument). This is the same order that Python requires.

/

The preceding parameters can only be supplied as positional arguments.

positional or keyword arguments:

All parameters until following / (if its supplied) but before */#*/#** can be supplied positionally or by keyword. Optional arguments may be given as two-argument lists, where the first element is the parameter name and the second is the default value. When defining parameters, a positional argument cannot follow a keyword argument.

The following example defines a function with one required positional argument as well as three optional arguments. The first optional argument defaults to None and the latter two default to "(" and ")", respectively:

=> (defn format-pair [left-val [right-val None] [open-text "("] [close-text ")"]]
...  (+ open-text (str left-val) ", " (str right-val) close-text))

=> (format-pair 3)
'(3, None)'

=> (format-pair "A" "B")
'(A, B)'

=> (format-pair "A" "B" "<" ">")
'<A, B>'

=> (format-pair "A" :open-text "<" :close-text ">")
'<A, None>'
#*

The following parameter will contain a list of 0 or more positional arguments. No other positional parameters may be specified after this one. Parameters defined after this but before #** are considered keyword only.

The following code example defines a function that can be given 0 to n numerical parameters. It then sums every odd number and subtracts every even number:

=> (defn zig-zag-sum [#* numbers]
     (setv odd-numbers (lfor x numbers :if (odd? x) x)
           even-numbers (lfor x numbers :if (even? x) x))
     (- (sum odd-numbers) (sum even-numbers)))

=> (zig-zag-sum)
0
=> (zig-zag-sum 3 9 4)
8
=> (zig-zag-sum 1 2 3 4 5 6)
-3
  • All following parmaeters can only be supplied as keywords. Like keyword arguments, the parameter may be marked as optional by declaring it as a two-element list containing the parameter name following by the default value. Parameters without a default are considered required:

    => (defn compare [a b * keyfn [reverse False]]
    ...  (setv result (keyfn a b))
    ...  (if (not reverse)
    ...    result
    ...    (- result)))
    => (compare "lisp" "python"
    ...         :keyfn (fn [x y]
    ...                  (reduce - (map (fn [s] (ord (first s))) [x y]))))
    -4
    => (compare "lisp" "python"
    ...         :keyfn (fn [x y]
    ...                   (reduce - (map (fn [s] (ord (first s))) [x y])))
    ...         :reverse True)
    4
    
    => (compare "lisp" "python")
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    TypeError: compare() missing 1 required keyword-only argument: 'keyfn'
    
#**

Like #*, but for keyword arguments. The following parameter will contain 0 or more keyword arguments.

The following code examples defines a function that will print all keyword arguments and their values:

=> (defn print-parameters [#** kwargs]
...    (for [(, k v) (.items kwargs)] (print k v)))

=> (print-parameters :parameter-1 1 :parameter-2 2)
parameter_1 1
parameter_2 2

; to avoid the mangling of '-' to '_', use unpacking:
=> (print-parameters #** {"parameter-1" 1 "parameter-2" 2})
parameter-1 1
parameter-2 2

Examples

The following example uses all of /, #*, and #** in order to show their interactions with each other. The function renders an HTML tag. It requires positional only argument tag-name, a string which is the tag name. It has one optional argument, delim, which defaults to "" and is placed between each child. The rest of the arguments, children, are the tag’s children or content. A single keyword-only argument, empty, is included and defaults to False. empty changes how the tag is rendered if it has no children. Normally, a tag with no children is rendered like <div></div>. If empty is True, then it will render like <div />. The rest of the keyword arguments, props, render as HTML attributes:

=> (defn render-html-tag [tag-name / [delim ""] #* children [empty False] #** attrs]
...  (setv rendered-attrs (.join " " (lfor (, key val) (.items attrs) (+ (unmangle (str key)) "="" (str val) """))))
...  (if rendered-attrs  ; If we have attributes, prefix them with a space after the tag name
...    (setv rendered-attrs (+ " " rendered-attrs)))
...  (setv rendered-children (.join delim children))
...  (if (and (not children) empty)
...    (+ "<" tag-name rendered-attrs " />")
...    (+ "<" tag-name rendered-attrs ">" rendered-children "</" tag-name ">")))
=> (render-html-tag "div")
'<div></div'>
=> (render-html-tag "img" :empty True)
'<img />'
=> (render-html-tag "img" :id "china" :class "big-image" :empty True)
'<img id="china" class="big-image" />'
=> (render-html-tag "p" " --- " (render-html-tag "span" "" :class "fancy" "I'm fancy!") "I'm to the right of fancy" "I'm alone :(")
'<p><span class="fancy">I'm fancy!</span> --- I'm to right right of fancy --- I'm alone :(</p>'
(defn/a name lambda-list #* body)

Define name as a function with lambda-list signature and body body.

defn/a macro is a variant of defn that instead defines coroutines. It takes three parameters: the name of the function to define, a vector of parameters, and the body of the function:

Examples

=> (defn/a name [params] body)
(if #* args)

Conditionally evaluate alternating test and then expressions.

if / if* respect Python truthiness, that is, a test fails if it evaluates to a “zero” (including values of len zero, None, and False), and passes otherwise, but values with a __bool__ method can override this.

The if macro is for conditionally selecting an expression for evaluation. The result of the selected expression becomes the result of the entire if form. if can select a group of expressions with the help of a do block.

if takes any number of alternating test and then expressions, plus an optional else expression at the end, which defaults to None. if checks each test in turn, and selects the then corresponding to the first passed test. if does not evaluate any expressions following its selection, similar to the if/elif/else control structure from Python. If no tests pass, if selects else.

Examples

=> (print (if (< n 0.0) "negative"
           (= n 0.0) "zero"
           (> n 0.0) "positive"
           "not a number"))
=> (if* (money-left? account)
      (print "let's go shopping")
      (print "let's go and work"))
##@( &name expr)

with-decorator tag macro

(-> head #* args)

Thread head first through the rest of the forms.

-> (or the threading macro) is used to avoid nesting of expressions. The threading macro inserts each expression into the next expression’s first argument place. The following code demonstrates this:

Examples

=> (defn output [a b] (print a b))
=> (-> (+ 4 6) (output 5))
10 5
(->> head #* args)

Thread head last through the rest of the forms.

->> (or the threading tail macro) is similar to the threading macro, but instead of inserting each expression into the next expression’s first argument, it appends it as the last argument. The following code demonstrates this:

Examples

=> (defn output [a b] (print a b))
=> (->> (+ 4 6) (output 5))
5 10
(as-> head name #* rest)

Beginning with head, expand a sequence of assignments rest to name.

New in version 0.12.0.

Each assignment is passed to the subsequent form. Returns the final assignment, leaving the name bound to it in the local scope.

This behaves similarly to other threading macros, but requires specifying the threading point per-form via the name, rather than fixing to the first or last argument.

Examples

example how -> and as-> relate:

=> (as-> 0 it
...      (inc it)
...      (inc it))
2
=> (-> 0 inc inc)
2

create data for our cuttlefish database:

=> (setv data [{:name "hooded cuttlefish"
...             :classification {:subgenus "Acanthosepion"
...                              :species "Sepia prashadi"}
...             :discovered {:year 1936
...                          :name "Ronald Winckworth"}}
...            {:name "slender cuttlefish"
...             :classification {:subgenus "Doratosepion"
...                              :species "Sepia braggi"}
...             :discovered {:year 1907
...                          :name "Sir Joseph Cooke Verco"}}])

retrieve name of first entry:

=> (as-> (first data) it
...      (:name it))
"hooded cuttlefish"

retrieve species of first entry:

=> (as-> (first data) it
...      (:classification it)
...      (:species it))
"Sepia prashadi"

find out who discovered slender cuttlefish:

=> (as-> (filter (fn [entry] (= (:name entry)
...                           "slender cuttlefish")) data) it
...      (first it)
...      (:discovered it)
...      (:name it))
"Sir Joseph Cooke Verco"

more convoluted example to load web page and retrieve data from it:

=> (import [urllib.request [urlopen]])
=> (as-> (urlopen "http://docs.hylang.org/en/stable/") it
...      (.read it)
...      (.decode it "utf-8")
...      (drop (.index it "Welcome") it)
...      (take 30 it)
...      (list it)
...      (.join "" it))
"Welcome to Hy’s documentation!"

Note

In these examples, the REPL will report a tuple (e.g. (‘Sepia prashadi’, ‘Sepia prashadi’)) as the result, but only a single value is actually returned.

(assoc coll k1 v1 #* other-kvs)

Associate key/index value pair(s) to a collection coll like a dict or list.

assoc is used to associate a key with a value in a dictionary or to set an index of a list to a value. It takes at least three parameters: the data structure to be modified, a key or index, and a value. If more than three parameters are used, it will associate in pairs.

Examples

=> (do
...   (setv collection {})
...   (assoc collection "Dog" "Bark")
...   (print collection))
{u'Dog': u'Bark'}
=> (do
...   (setv collection {})
...   (assoc collection "Dog" "Bark" "Cat" "Meow")
...   (print collection))
{u'Cat': u'Meow', u'Dog': u'Bark'}
=> (do
...   (setv collection [1 2 3 4])
...   (assoc collection 2 None)
...   (print collection))
[1, 2, None, 4]

Note

assoc modifies the datastructure in place and returns None.

(cfor f #* generator)

syntactic sugar for passing a generator expression to the callable f

Its syntax is the same as generator expression, but takes a function f that the generator will be immedietly passed to. Equivalent to (f (gfor ...)).

Examples:

=> (cfor tuple x (range 10) :if (odd? x) x)
(, 1 3 5 7 9)

The equivalent in python would be:

>>> tuple(x for x in range(10) if is_odd(x))

Some other common functions that take iterables:

=> (cfor all x [1 3 8 5] (< x 10))
True

=> (with [f (open "AUTHORS")]
...  (cfor max
...        author (.splitlines (f.read))
...        :setv name (.group (re.match r"\* (.*?) <" author) 1)
...        :if (name.startswith "A")
...        (len name)))
20 ;; The number of characters in the longest author's name that starts with 'A'
(comment #* body)

Ignores body and always expands to None

The comment macro ignores its body and always expands to None. Unlike linewise comments, the body of the comment macro must be grammatically valid Hy, so the compiler can tell where the comment ends. Besides the semicolon linewise comments, Hy also has the #_ discard prefix syntax to discard the next form. This is completely discarded and doesn’t expand to anything, not even None.

Examples

=> (print (comment <h1>Surprise!</h1>
...                <p>You'd be surprised what's grammatically valid in Hy.</p>
...                <p>(Keep delimiters in balance, and you're mostly good to go.)</p>)
...        "Hy")
None Hy
=> (print #_(comment <h1>Surprise!</h1>
...                  <p>You'd be surprised what's grammatically valid in Hy.</p>
...                  <p>(Keep delimiters in balance, and you're mostly good to go.)</p>))
...        "Hy")
Hy
(cond #* branches)

Build a nested if clause with each branch a [cond result] bracket pair.

Examples

=> (cond [condition-1 result-1]
...      [condition-2 result-2])
(if condition-1 result-1
  (if condition-2 result-2))

If only the condition is given in a branch, then the condition is also used as the result. The expansion of this single argument version is demonstrated below:

=> (cond [condition-1]
...       [condition-2])
(if condition-1 condition-1
  (if condition-2 condition-2))

As shown below, only the first matching result block is executed:

=> (defn check-value [value]
...   (cond [(< value 5) (print "value is smaller than 5")]
...         [(= value 5) (print "value is equal to 5")]
...         [(> value 5) (print "value is greater than 5")]
...         [True (print "value is something that it should not be")]))

=> (check-value 6)
"value is greater than 5"
(defmacro! name args #* body)

Like defmacro/g!, with automatic once-only evaluation for ‘o!’ params.

Such ‘o!’ params are available within body as the equivalent ‘g!’ symbol.

Examples

=> (defn expensive-get-number [] (print "spam") 14)
=> (defmacro triple-1 [n] `(+ ~n ~n ~n))
=> (triple-1 (expensive-get-number))  ; evals n three times
spam
spam
spam
42
=> (defmacro/g! triple-2 [n] `(do (setv ~g!n ~n) (+ ~g!n ~g!n ~g!n)))
=> (triple-2 (expensive-get-number))  ; avoid repeats with a gensym
spam
42
=> (defmacro! triple-3 [o!n] `(+ ~g!n ~g!n ~g!n))
=> (triple-3 (expensive-get-number))  ; easier with defmacro!
spam
42
(defmacro/g! name args #* body)

Like defmacro, but symbols prefixed with ‘g!’ are gensymed.

New in version 0.9.12.

defmacro/g! is a special version of defmacro that is used to automatically generate gensym for any symbol that starts with g!.

For example, g!a would become (gensym "a").

(defmain args #* body)

Write a function named “main” and do the ‘if __main__’ dance.

New in version 0.10.1.

The defmain macro defines a main function that is immediately called with sys.argv as arguments if and only if this file is being executed as a script. In other words, this:

Examples

=> (defmain [#* args]
...  (do-something-with args))

is the equivalent of:

=> def main(*args):
...    do_something_with(args)
...    return 0
...
... if __name__ == "__main__":
...     import sys
...     retval = main(*sys.argv)
...
...     if isinstance(retval, int):
...         sys.exit(retval)

Note that as you can see above, if you return an integer from this function, this will be used as the exit status for your script. (Python defaults to exit status 0 otherwise, which means everything’s okay!) Since (sys.exit 0) is not run explicitly in the case of a non-integer return from defmain, it’s a good idea to put (defmain) as the last piece of code in your file.

If you want fancy command-line arguments, you can use the standard Python module argparse in the usual way:

=> (import argparse)
=> (defmain [#* _]
...   (setv parser (argparse.ArgumentParser))
...   (.add-argument parser "STRING"
...     :help "string to replicate")
...   (.add-argument parser "-n" :type int :default 3
...     :help "number of copies")
...   (setv args (parser.parse_args))
...   (print (* args.STRING args.n))
...   0)
(do-n count-form #* body)

Execute body a number of times equal to count-form and return None. (To collect return values, use list-n instead.) Negative values of the count are treated as 0.

This macro is implemented as a for loop, so you can use break and continue in the body.

=> (do-n 3 (print "hi"))
hi
hi
hi
(doc symbol)

macro documentation

Gets help for a macro function available in this module. Use require to make other macros available.

Use (help foo) instead for help with runtime objects.

(doto form #* expressions)

Perform possibly mutating expressions on form, returning resulting obj.

New in version 0.10.1.

doto is used to simplify a sequence of method calls to an object.

Examples

=> (doto [] (.append 1) (.append 2) .reverse)
[2, 1]
=> (setv collection [])
=> (.append collection 1)
=> (.append collection 2)
=> (.reverse collection)
=> collection
[2, 1]
(if-not test not-branch yes-branch)

Like if, but execute the first branch when the test fails

New in version 0.10.0.

if-not is similar to if* but the second expression will be executed when the condition fails while the third and final expression is executed when the test succeeds – the opposite order of if*. The final expression is again optional and defaults to None.

Examples

=> (if-not (money-left? account)
      (print "let's go and work")
      (print "let's go shopping"))
(lif #* args)

Like if, but anything that is not None is considered true.

New in version 0.10.0.

For those that prefer a more Lispy if clause, we have lif. This only considers None to be false! All other “false-ish” Python values are considered true.

Examples

=> (lif True "true" "false")
"true"
=> (lif False "true" "false")
"true"
=> (lif 0 "true" "false")
"true"
=> (lif None "true" "false")
"false"
(lif-not test not-branch yes-branch)

Like if-not, but anything that is not None is considered true.

New in version 0.11.0.

Examples

=> (lif-not None "true" "false")
"true"
=> (lif-not False "true" "false")
"false"
(list-n count-form #* body)

Like do-n, but the results are collected into a list.

=> (setv counter 0)
=> (list-n 5 (+= counter 1) counter)
[1 2 3 4 5]
(of base #* args)

Shorthand for indexing for type annotations.

If only one arguments are given, this expands to just that argument. If two arguments are given, it expands to indexing the first argument via the second. Otherwise, the first argument is indexed using a tuple of the rest.

of has three forms:

  • (of T) will simply become T.

  • (of T x) will become (get T x).

  • (of T x y ...) (where the ... represents zero or more arguments) will become (get T (, x y ...)).

Examples

=> (of str)
str
=> (of List int)
List[int]
=> (of Set int)
Set[int]
=> (of Dict str str)
Dict[str, str]
=> (of Tuple str int)
Tuple[str, int]
=> (of Callable [int str] str)
Callable[[int, str], str]
(unless test #* body)

Execute body when test is false

The unless macro is a shorthand for writing an if statement that checks if the given conditional is False. The following shows the expansion of this macro.

Examples

=> (unless conditional statement)
(if conditional
  None
  (do statement))
(when test #* body)

Execute body when test is true

when is similar to unless, except it tests when the given conditional is True. It is not possible to have an else block in a when macro. The following shows the expansion of the macro.

Examples

=> (when conditional statement)
(if conditional (do statement))
(with-gensyms args #* body)

Execute body with args as bracket of names to gensym for use in macros.

New in version 0.9.12.

with-gensym is used to generate a set of gensym for use in a macro. The following code:

Examples

=> (with-gensyms [a b c]
...   ...)

expands to:

=> (do
...   (setv a (gensym)
...         b (gensym)
...         c (gensym))
...   ...)

Extra

Anaphoric

New in version 0.9.12.

The anaphoric macros module makes functional programming in Hy very concise and easy to read.

An anaphoric macro is a type of programming macro that deliberately captures some form supplied to the macro which may be referred to by an anaphor (an expression referring to another).

—Wikipedia (https://en.wikipedia.org/wiki/Anaphoric_macro)

To use these macros you need to require the hy.extra.anaphoric module like so:

(require [hy.extra.anaphoric [*]])

These macros are implemented by replacing any use of the designated anaphoric symbols (it, in most cases) with a gensym. Consequently, it’s unwise to nest these macros where symbol replacement is happening. Symbol replacement typically takes place in body or form parameters, where the output of the expression may be returned. It is also recommended to avoid using an affected symbol as something other than a variable name, as in (print "My favorite Stephen King book is" 'it).

##%( &name expr)

Makes an expression into a function with an implicit % parameter list.

A %i symbol designates the (1-based) i th parameter (such as %3). Only the maximum %i determines the number of %i parameters–the others need not appear in the expression. %* and %** name the #* and #** parameters, respectively.

Examples

=> (#%[%1 %6 42 [%2 %3] %* %4] 1 2 3 4 555 6 7 8)
[1, 6, 42, [2, 3], (7, 8), 4]
=> (#% %** :foo 2)
{"foo": 2}

When used on an s-expression, #% is similar to Clojure’s anonymous function literals–#():

=> (setv add-10 #%(+ 10 %1))
=> (add-10 6)
16

Note

#% determines the parameter list by the presence of a %* or %** symbol and by the maximum %i symbol found anywhere in the expression, so nesting of #% forms is not recommended.

(ap-dotimes n #* body)

Equivalent to (ap-each (range n) body…).

Examples

=> (setv n [])
=> (ap-dotimes 3 (.append n it))
=> n
[0, 1, 2]
(ap-each xs #* body)

Evaluate the body forms for each element it of xs and return None.

Examples

=> (ap-each [1 2 3] (print it))
1
2
3
(ap-each-while xs form #* body)

As ap-each, but the form pred is run before the body forms on each iteration, and the loop ends if pred is false.

Examples

=> (ap-each-while [1 2 3 4 5 6] (< it 4) (print it))
1
2
3
(ap-filter form xs)

The filter() equivalent of ap-map.

Examples

=> (list (ap-filter (> (* it 2) 6) [1 2 3 4 5]))
[4, 5]
(ap-first form xs)

Evaluate the predicate form for each element it of xs. When the predicate is true, stop and return it. If the predicate is never true, return None.

Examples

=> (ap-first (> it 5) (range 10))
6
(ap-if test-form then-form else-form)

As if, but the result of the test form is named it in the subsequent forms. As with if, the else-clause is optional.

Examples

=> (import os)
=> (ap-if (.get os.environ "PYTHONPATH")
...   (print "Your PYTHONPATH is" it))
(ap-last form xs)

Usage: (ap-last form list)

Evaluate the predicate form for every element it of xs. Return the last element for which the predicate is true, or None if there is no such element.

Examples

=> (ap-last (> it 5) (range 10))
9
(ap-map form xs)

Create a generator like map() that yields each result of form evaluated with it bound to successive elements of xs.

Examples

=> (list (ap-map (* it 2) [1 2 3]))
[2, 4, 6]
(ap-map-when predfn rep xs)

As ap-map, but the predicate function predfn (yes, that’s a function, not an anaphoric form) is applied to each it, and the anaphoric mapping form rep is only applied if the predicate is true. Otherwise, it is yielded unchanged.

Examples

=> (list (ap-map-when odd? (* it 2) [1 2 3 4]))
[2, 2, 6, 4]
=> (list (ap-map-when even? (* it 2) [1 2 3 4]))
[1, 4, 3, 8]
(ap-reduce form o!xs initial-value)

This macro is an anaphoric version of reduce(). It works as follows:

  • Bind acc to the first element of xs, bind it to the second, and evaluate form.

  • Bind acc to the result, bind it to the third value of xs, and evaluate form again.

  • Bind acc to the result, and continue until xs is exhausted.

If initial-value is supplied, the process instead begins with acc set to initial-value and it set to the first element of xs.

Examples

=> (ap-reduce (+ it acc) (range 10))
45
(ap-reject form xs)

Equivalent to (ap-filter (not form) xs).

Examples

=> (list (ap-reject (> (* it 2) 6) [1 2 3 4 5]))
[1, 2, 3]
(recur-sym-replace d form)

Recursive symbol replacement.

(rit #* body)

Supply it as a gensym and R as a function to replace it with the given gensym throughout expressions.

Reserved

(names)

Return a frozenset of reserved symbol names.

The result of the first call is cached.

This function can be used to get a list (actually, a frozenset) of the names of Hy’s built-in functions, macros, and special forms. The output also includes hy.extra.reserved.special and all Python reserved words. All names are in unmangled form (e.g., not-in rather than not_in).

Examples

=> (import hy.extra.reserved)
=> (in "defclass" (hy.extra.reserved.names))
True
(special)

Return a frozenset of special operators, such as fn and +.

Contributor Modules

Sequences

New in version 0.12.0.

The sequences module contains a few macros for declaring sequences that are evaluated only as much as the client code requires. Unlike generators, they allow accessing the same element multiple times. They cache calculated values, and the implementation allows for recursive definition of sequences without resulting in recursive computation.

To use these macros, you need to require them and import some other names like so:

(require [hy.contrib.sequences [defseq seq]])
(import [hy.contrib.sequences [Sequence end-sequence]])

The simplest sequence can be defined as (seq [n] n). This defines a sequence that starts as [0 1 2 3 ...] and continues forever. In order to define a finite sequence, you need to call end-sequence to signal the end of the sequence:

(seq [n]
     "sequence of 5 integers"
     (cond [(< n 5) n]
           [True (end-sequence)]))

This creates the following sequence: [0 1 2 3 4]. For such a sequence, len returns the amount of items in the sequence and negative indexing is supported. Because both of these require evaluating the whole sequence, calling one on an infinite sequence would take forever (or at least until available memory has been exhausted).

Sequences can be defined recursively. For example, the Fibonacci sequence could be defined as:

(defseq fibonacci [n]
  "infinite sequence of fibonacci numbers"
  (cond [(= n 0) 0]
        [(= n 1) 1]
        [True (+ (get fibonacci (- n 1))
                 (get fibonacci (- n 2)))]))

This results in the sequence [0 1 1 2 3 5 8 13 21 34 ...].

class (Sequence func)

Container for construction of lazy sequences.

(defseq seq-name param #* seq-code)

Creates a sequence defined in terms of n and assigns it to a given name.

Examples

=> (defseq numbers [n] n)

(end-sequence)

Signals the end of a sequence when an iterator reaches the given point of the sequence.

Internally, this is done by raising IndexError, catching that in the iterator, and raising StopIteration

Examples

=> (seq [n] (if (< n 5) n (end-sequence)))
Raises

IndexError – to signal end of sequence

(seq param #* seq-code)

Creates a sequence defined in terms of n.

Examples

=> (seq [n] (* n n))

Walk

Hy AST walker

New in version 0.11.0.

(call? form)

Checks whether form is a non-empty hy.models.Expression

(lambda-list form)

splits a fn argument list into sections based on &-headers.

returns an OrderedDict mapping headers to sublists. Arguments without a header are under None.

(let bindings #* body)

sets up lexical bindings in its body

let creates lexically-scoped names for local variables. A let-bound name ceases to refer to that local outside the let form. Arguments in nested functions and bindings in nested let forms can shadow these names.

Examples

=> (let [x 5]  ; creates a new local bound to name 'x
...  (print x)
...  (let [x 6]  ; new local and name binding that shadows 'x
...    (print x))
...  (print x))  ; 'x refers to the first local again
5
6
5

Basic assignments (e.g. setv, +=) will update the local variable named by a let binding, when they assign to a let-bound name.

But assignments via import are always hoisted to normal Python scope, and likewise, defclass will assign the class to the Python scope, even if it shares the name of a let binding.

Use importlib.import_module and type (or whatever metaclass) instead, if you must avoid this hoisting.

The let macro takes two parameters: a list defining variables and the body which gets executed. variables is a vector of variable and value pairs. let can also define variables using Python’s extended iterable unpacking syntax to destructure iterables:

=> (let [[head #* tail] (, 0 1 2)]
...   [head tail])
[0 [1 2]]

Do note, however, that let can not destructure into a mutable data type, such as dicts or classes. As such, the following will both raise macro expansion errors:

Unpack into dictionary:

=> (let [x (dict)
...      (, a (get x "y")) [1 2]]
...  [a x])

Unpack into a class:

=> (let [x (SimpleNamespace)
...      [a x.y] [1 2]]
...  [a x])

Like the let* of many other Lisps, let executes the variable assignments one-by-one, in the order written:

=> (let [x 5
...       y (+ x 1)]
...   (print x y))
5 6

Unlike them, however, each (let …) form uses only one namespace for all its assignments. Thus, (let [x 1  x (fn [] x)] (x)) returns a function object, not 1 as you might expect.

It is an error to use a let-bound name in a global or nonlocal form.

(macroexpand-all form module-name)

Recursively performs all possible macroexpansions in form, using the require context of module-name. macroexpand-all assumes the calling module’s context if unspecified.

(postwalk f form)

Performs depth-first, post-order traversal of form. Calls f on each sub-form, uses f ‘s return value in place of the original.

Examples

=> (import [hy.contrib.walk [postwalk]])
=> (setv trail '([1 2 3] [4 [5 6 [7]]]))
=> (defn walking [x]
...   (print "Walking" x :sep "\n")
...   x)
=> (postwalk walking trail)
Walking
1
Walking
2
Walking
3
Walking
hy.models.Expression([
  hy.models.Integer(1),
  hy.models.Integer(2),
  hy.models.Integer(3)])
Walking
4
Walking
5
Walking
6
Walking
7
Walking
hy.models.Expression([
  hy.models.Integer(7)])
Walking
hy.models.Expression([
  hy.models.Integer(5),
  hy.models.Integer(6),
  hy.models.List([
    hy.models.Integer(7)])])
Walking
hy.models.Expression([
  hy.models.Integer(4),
  hy.models.List([
    hy.models.Integer(5),
    hy.models.Integer(6),
    hy.models.List([
      hy.models.Integer(7)])])])
Walking
hy.models.Expression([
  hy.models.List([
    hy.models.Integer(1),
    hy.models.Integer(2),
    hy.models.Integer(3)]),
  hy.models.List([
    hy.models.Integer(4),
    hy.models.List([
      hy.models.Integer(5),
      hy.models.Integer(6),
      hy.models.List([
        hy.models.Integer(7)])])])])
hy.models.Expression([
  hy.models.List([
    hy.models.Integer(1),
    hy.models.Integer(2),
    hy.models.Integer(3)]),
  hy.models.List([
    hy.models.Integer(4),
    hy.models.List([
      hy.models.Integer(5),
      hy.models.Integer(6),
      hy.models.List([
        hy.models.Integer(7)])])])])
(prewalk f form)

Performs depth-first, pre-order traversal of form. Calls f on each sub-form, uses f ‘s return value in place of the original.

Examples

=> (import [hy.contrib.walk [prewalk]])
=> (setv trail '([1 2 3] [4 [5 6 [7]]]))
=> (defn walking [x]
...  (print "Walking" x :sep "\n")
...  x)
=> (prewalk walking trail)
Walking
hy.models.Expression([
  hy.models.List([
    hy.models.Integer(1),
    hy.models.Integer(2),
    hy.models.Integer(3)]),
  hy.models.List([
    hy.models.Integer(4),
    hy.models.List([
      hy.models.Integer(5),
      hy.models.Integer(6),
      hy.models.List([
        hy.models.Integer(7)])])])])
Walking
hy.models.List([
  hy.models.Integer(1),
  hy.models.Integer(2),
  hy.models.Integer(3)])
Walking
1
Walking
2
Walking
3
Walking
hy.models.List([
  hy.models.Integer(4),
  hy.models.List([
    hy.models.Integer(5),
    hy.models.Integer(6),
    hy.models.List([
      hy.models.Integer(7)])])])
Walking
4
Walking
hy.models.List([
  hy.models.Integer(5),
  hy.models.Integer(6),
  hy.models.List([
    hy.models.Integer(7)])])
Walking
5
Walking
6
Walking
hy.models.List([
  hy.models.Integer(7)])
Walking
7
hy.models.Expression([
  hy.models.List([
    hy.models.Integer(1),
    hy.models.Integer(2),
    hy.models.Integer(3)]),
  hy.models.List([
    hy.models.Integer(4),
    hy.models.List([
      hy.models.Integer(5),
      hy.models.Integer(6),
      hy.models.List([
        hy.models.Integer(7)])])])])
(smacrolet bindings #* body)

symbol macro let.

Replaces symbols in body, but only where it would be a valid let binding. The bindings pairs the target symbol and the expansion form for that symbol.

(walk inner outer form)

walk traverses form, an arbitrary data structure. Applies inner to each element of form, building up a data structure of the same type. Applies outer to the result.

Examples

=> (import [hy.contrib.walk [walk]])
=> (setv a '(a b c d e f))
=> (walk ord identity a)
hy.models.Expression([
  97,
  98,
  99,
  100,
  101,
  102])
=> (walk ord first a)
97

Profile

Hy Profiling macros

These macros make debugging where bottlenecks exist easier.

(profile/calls #* body)

profile/calls allows you to create a call graph visualization. Note: You must have Graphviz installed for this to work.

Examples

=> (require [hy.contrib.profile [profile/calls]])
=> (profile/calls (print "hey there"))
(profile/cpu #* body)

Profile a bit of code

Examples

=> (require [hy.contrib.profile [profile/cpu]])
=> (profile/cpu (print "hey there"))
hey there
<pstats.Stats instance at 0x14ff320>
          2 function calls in 0.000 seconds

  Random listing order was used

  ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      1    0.000    0.000    0.000    0.000 {print}

Loop

The loop/recur macro allows you to construct functions that use tail-call optimization to allow arbitrary levels of recursion.

New in version 0.10.0.

The loop / recur macro gives programmers a simple way to use tail-call optimization (TCO) in their Hy code.

A tail call is a subroutine call that happens inside another procedure as its final action; it may produce a return value which is then immediately returned by the calling procedure. If any call that a subroutine performs, such that it might eventually lead to this same subroutine being called again down the call chain, is in tail position, such a subroutine is said to be tail-recursive, which is a special case of recursion. Tail calls are significant because they can be implemented without adding a new stack frame to the call stack. Most of the frame of the current procedure is not needed any more, and it can be replaced by the frame of the tail call. The program can then jump to the called subroutine. Producing such code instead of a standard call sequence is called tail call elimination, or tail call optimization. Tail call elimination allows procedure calls in tail position to be implemented as efficiently as goto statements, thus allowing efficient structured programming.

—Wikipedia (https://en.wikipedia.org/wiki/Tail_call)

(loop bindings #* body)

loop establishes a recursion point. With loop, recur rebinds the variables set in the recursion point and sends code execution back to that recursion point. If recur is used in a non-tail position, an exception is raised. which causes chaos.

Usage: (loop bindings #* body)

Examples

=> (require [hy.contrib.loop [loop]])
=> (defn factorial [n]
...  (loop [[i n] [acc 1]]
...    (if (zero? i)
...      acc
...      (recur (dec i) (* acc i)))))
=> (factorial 1000)

Hy Repr

New in version 0.13.0.

hy.contrib.hy-repr is a module containing two functions. To import them, say:

(import [hy.contrib.hy-repr [hy-repr hy-repr-register]])

To make the Hy REPL use it for output, invoke Hy like so:

$ hy --repl-output-fn=hy.contrib.hy-repr.hy-repr
(hy-repr obj)

This function is Hy’s equivalent of Python’s built-in repr. It returns a string representing the input object in Hy syntax.

Like repr in Python, hy-repr can round-trip many kinds of values. Round-tripping implies that given an object x, (hy.eval (read-str (hy-repr x))) returns x, or at least a value that’s equal to x.

Examples

=> hy-repr [1 2 3])
'[1 2 3]'
=> (repr [1 2 3])
'[1, 2, 3]'
(hy-repr-register types f placeholder)

hy-repr-register lets you set the function that hy-repr calls to represent a type.

Examples

 => (hy-repr-register the-type fun)

 => (defclass C)
 => (hy-repr-register C (fn [x] "cuddles"))
 => (hy-repr [1 (C) 2])
 '[1 cuddles 2]'

 If the type of an object passed to ``hy-repr`` doesn't have a registered
 function, ``hy-repr`` will search the type's method resolution order
 (its ``__mro__`` attribute) for the first type that does. If ``hy-repr``
 doesn't find a candidate, it falls back on ``repr``.

 Registered functions often call ``hy-repr`` themselves. ``hy-repr`` will
 automatically detect self-references, even deeply nested ones, and
 output ``"..."`` for them instead of calling the usual registered
 function. To use a placeholder other than ``"..."``, pass a string of
 your choice to the keyword argument ``:placeholder`` of
 ``hy-repr-register``.

=> (defclass Container [object]
...   (defn __init__ (fn [self value]
...     (setv self.value value))))
=>    (hy-repr-register Container :placeholder "HY THERE" (fn [x]
...      (+ "(Container " (hy-repr x.value) ")")))
=> (setv container (Container 5))
=> (setv container.value container)
=> (print (hy-repr container))
"(Container HY THERE)"

PPrint

hy.contrib.pprint is a port of python’s built-in pprint that can pretty print objects using Hy syntax.

Hy pprint leverages hy-repr for much of it’s pretty printing and therefor can be extended to work with arbitrary types using hy-repr-register. Like Python’s pprint and hy-repr, Hy pprint attempts to maintain round-trippability of it’s input where possible. Unlike Python, however, Hy does not have string literal concatenation, which is why strings and bytestrings are broken up using the form (+ ...).

The API for Hy pprint is functionally identical to Python’s pprint module, so be sure to reference the Python pprint docs for more on how to use the module’s various methods and arguments.

The differences that do exist are as follows:

  • isreadable becomes readable?

  • isrecursive becomes recursive?

  • Passing False to the PrettyPrinter arg sort-dicts in Python versions < 3.8 will raise a ValueError

class (PrettyPrinter [indent 1]  [width 80] depth stream *  [compact False]  [sort-dicts True])

Handle pretty printing operations onto a stream using a set of configured parameters.

Parameters
  • indent – Number of spaces to indent for each level of nesting.

  • width – Attempted maximum number of columns in the output.

  • depth – The maximum depth to print out nested structures.

  • stream – The desired output stream. If omitted (or false), the standard output stream available at construction will be used.

  • compact – If true, several items will be combined in one line.

  • sort-dicts – If True, dict keys are sorted. (only available for python >= 3.8)

(format object context maxlevels level)

Format object for a specific context, returning a string and flags indicating whether the representation is ‘readable’ and whether the object represents a recursive construct.

(pformat object #* args #** kwargs)

Format a Python object into a pretty-printed representation.

(pp object [sort-dicts False] #* args #** kwargs)

Pretty-print a Python object

(pprint object #* args #** kwargs)

Pretty-print a Python object to a stream [default is sys.stdout].

Examples

=> (pprint {:name "Adam" :favorite-foods #{:apple :pizza}
              :bio "something very important"}
      :width 20)
 {:name "Adam"
  :bio (+ "something "
          "very "
          "important")
  :favorite-foods #{:apple
                    :pizza}}
(readable? object)

Determine if (saferepr object) is readable by (hy.eval).

(recursive? object)

Determine if object requires a recursive representation.

(saferepr object)

Version of (repr) which can handle recursive data structures.

Destructure

This module is heavily inspired by destructuring from Clojure and provides very similar semantics. It provides several macros that allow for destructuring within their arguments.

Introduction

To use these macros, you need to require them like so:

(require [hy.contrib.destructure [setv+ fn+ defn+ let+ defn/a+ fn/a+]])

Destructuring allows one to easily peek inside a data structure and assign names to values within. For example,

(setv+ {[{name :name [weapon1 weapon2] :weapons} :as all-players] :players
        map-name :map
        :keys [tasks-remaining tasks-completed]}
       data)

would be equivalent to

(setv map-name (.get data ':map)
      tasks-remaining (.get data ':tasks-remaining)
      tasks-completed (.get data ':tasks-completed)
      all-players (.get data ':players)
      name (.get (nth all-players 0) ':name)
      weapon1 (get (.get (nth all-players 0) ':weapons) 0)
      weapon2 (get (.get (nth all-players 0) ':weapons) 1))

where data might be defined by

(setv data {:players [{:name Joe :weapons [:sword :dagger]}
                      {:name Max :weapons [:axe :crossbow]}]
            :map "Dungeon"
            :tasks-remaining 4})

This is similar to unpacking iterables in Python, such as a, *b, c = range(10), however it also works on dictionaries, and has several special options.

Patterns

Dictionary Pattern

Dictionary patterns are specified using dictionaries, where the keys corresponds to the symbols which are to be bound, and the values correspond to which key needs to be looked up in the expression for the given symbol.

(setv+ {a :a b "b" c (, 1 0)} {:a 1 "b" 2 (, 1 0) 3})
[a b c] ; => [1 2 3]

The keys can also be one of the following 4 special options: :or, :as, :keys, :strs.

  • :or takes a dictionary of default values.

  • :as takes a variable name which is bound to the entire expression.

  • :keys takes a list of variable names which are looked up as keywords in the expression.

  • :strs is the same as :keys but uses strings instead.

The ordering of the special options and the variable names doesn’t matter, however each special option can be used at most once.

(setv+ {:keys [a b] :strs [c d] :or {b 2 d 4} :as full} {:a 1 :b 2 "c" 3})
[a b c d full] ; => [1 2 3 4 {:a 1 :b 2 "c" 3}]

Variables which are not found in the expression are set to None if no default value is specified.

List Pattern

List patterns are specified using lists. The nth symbol in the pattern is bound to the nth value in the expression, or None if the expression has fewer than n values.

There are 2 special options: :& and :as.

  • :& takes a pattern which is bound to the rest of the expression. This pattern can be anything, including a dictionary, which allows for keyword arguments.

  • :as takes a variable name which is bound to the entire expression.

If the special options are present, they must be last, with :& preceding :as if both are present.

(setv+ [a b :& rest :as full] (range 5))
[a b rest full] ; => [0 1 [2 3 4] [0 1 2 3 4]]

(setv+ [a b :& {:keys [c d] :or {c 3}}] [1 2 :d 4 :e 5]
[a b c d] ; => [1 2 3 4]

Note that this pattern calls list on the expression before binding the variables, and hence cannot be used with infinite iterators.

Iterator Pattern

Iterator patterns are specified using round brackets. They are the same as list patterns, but can be safely used with infinite generators. The iterator pattern does not allow for recursive destructuring within the :as special option.

(defn+ fn-name args #* doc+body)

Define function fn-name with destructuring within args.

Note that #* etc have no special meaning and are intepretted as any other argument.

(defn/a+ fn-name args #* doc+body)

Async variant of defn+.

(dest-dict ddict result found binds gsyms)

Destructuring bind for mappings.

Binding forms may be nested. Targets from {} binds look up their value. For example, (destructure '{x :a  y :b} {:a 1  :b 2}) binds x to 1 and y to 2. To avoid duplication in common cases, the {:strs [foo bar]} option will look up “foo” and “bar” and bind them to the same name, just like {foo "foo" bar "bar"}. Similarly, :keys [foo bar] works like {foo :foo bar :bar}. Use the :as foo option to bind the whole mapping to foo. Use the :or {foo 42} option to to bind foo to 42 if foo is requested, but not present in expr.

(dest-iter diter result found binds gsyms)

Destructuring bind for iterables.

Binding forms may be nested. Unlike [] binds, () is safe for infinite iterators. Targets are assigned in order by pulling the next item from the iterator. Use the :& option to also return the remaining iterator. Use :as foo option in binds to bind a copy of the whole iterator using itertools.tee to foo. For example, try (destructure '(a b c :& more :as it) (count)).

(dest-list dlist result found binds gsyms)

Destructuring bind for random-access sequences.

Binding forms may be nested. Targets from [] binds are assigned by index order. Use :& bar option in binds to bind the remaining slice to bar. The :& argument can also be recursively destructed asdfasdf. Use :as foo option in binds to bind the whole iterable to foo. For example, try ``(destructure ‘[a b [c :& d :as q] :& {:keys [e f]} :as full]

[1 2 [3 4 5] :e 6 :f 7])``

(destructure binds expr gsyms)

Destructuring bind.

Implements the core logic, which would be useful for macros that want to make use of destructuring.

Binding forms may be nested. :as and :& are magic in [] and () binds. See dest-list and dest-iter. :as :or :strs and :keys are magic in {} binds. See des-dict.

In [] and () binds the magic keywords must come after the sequential symbols and :as must be last, if present.

(dict=: #* pairs)

Destructure into dict

Same as setv+, except returns a dictionary with symbols to be defined, instead of actually declaring them.

(fn+ args #* body)

Return anonymous function with destructuring within args

Note that *, /, etc have no special meaning and are intepretted as any other argument.

(fn/a+ args #* body)

Async variant of fn+.

(ifp o!pred o!expr #* clauses)

Takes a binary predicate pred, an expression expr, and a set of clauses. Each clause can be of the form cond res or cond :>> res. For each clause, if (pred cond expr) evaluates to true, returns res in the first case or (res (pred cond expr)) in the second case. If the last clause is just res, then it is returned as a default, else None.

Examples

=> (ifp instance? 5
...   str :string
...   int :int)
:int
=> (ifp = 4
...   3 :do-something
...   5 :do-something-else
...   :no-match)
:no-match
=> (ifp (fn [x f] (f x)) ':a
...   {:b 1} :>> inc
...   {:a 1} :>> dec)
0
(let+ args #* body)

let macro with full destructuring with args

(setv+ #* pairs)

Assignment with destructuring for both mappings and iterables.

Destructuring equivalent of setv. Binds symbols found in a pattern using the corresponding expression.

Examples

(setv+ pattern_1 expression_1 ...  pattern_n expression_n)

Slicing

Macros for elegantly slicing and dicing multi-axis and multidimensional sequences.

Libraries like numpy and pandas make extensive use of python’s slicing syntax and even extends it to allow multiple slices using tuples. This makes handling multi-axis (pandas) and multidimensional arrays (numpy) extremely elegant and efficient. Hy doesn’t support Python’s sugared slicing syntax (1::-2 # => slice(1, None, 2)). Which makes slicing quite cumbersome, especially when tuple’s get thrown into the mix. Hy’s cut form makes single slices easy, but anything more than that becomes much more difficult to construct and parse. Where python can express a multidimensional slice as:

>>> arr[1:-2:2,3:5,:]

The equivalent in Hy would be:

=> (get arr (, (slice 1 -2 2) (slice 3 5) (slice None)))

which is hardly ideal. This module provides an ncut macro and a #: tag macro that enable python’s sugared slicing form in Hy so that the previous could be expressed as:

=> (ncut a 1:-1:2 3:5 :)

or more manually using the tag macro as:

=> (get a (, #: 1:-2:2 #: 3:5 #: :))
##:( &name key)

Shorthand tag macro for constructing slices using Python’s sugared form.

Examples

=> #: 1:4:2
(slice 1 4 2)
=> (get [1 2 3 4 5] #: 2::2)
[3 5]

Numpy makes use of Ellipsis in its slicing semantics so they can also be constructed with this macro in their sugared ... form.

=> #: ...
Ellipsis

Slices can technically also contain strings (something pandas makes use of when slicing by string indices) and because Hy allows colons in identifiers, to construct these slices we have to use the form (...):

=> #:("colname" 1 2)
(slice "colname" 1 2)
(ncut seq key1 #* keys)

N-Dimensional cut macro with shorthand slice notation.

Libraries like numpy and pandas extend Python’s sequence slicing syntax to work with tuples to allow for elegant handling of multidimensional arrays (numpy) and multi-axis selections (pandas). A key in ncut can be any valid kind of index; specific, ranged, a numpy style mask. Any library can make use of tuple based slicing, so check with each lib for what is and isn’t valid.

Parameters
  • seq – Slicable sequence

  • key1 – A valid sequence index. What is valid can change from library to library.

  • *keys – Additional indices. Specifying more than one index will expand to a tuple allowing multi-dimensional indexing.

Examples

Single dimensional list slicing

=> (ncut (list (range 10)) 2:8:2)
[2 4 6]

numpy multidimensional slicing:

=> (setv a (.reshape (np.arange 36) (, 6 6)))
=> a
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])
=> (ncut a (, 0 1 2 3 4) (, 1 2 3 4 5))
array([ 1,  8, 15, 22, 29])
=> (ncut a 3: (, 0 2 5))
array([[18, 20, 23],
       [24, 26, 29],
       [30, 32, 35]])
=> (ncut a 1:-1:2 3:5)
array([[ 9, 10],
       [21, 22]])
=> (ncut a ::2 3 None)
array([[ 3],
       [15],
       [27]])
=> (ncut a ... 0)
array([ 0,  6, 12, 18, 24, 30])

Because variables can have colons in Hy (eg: abc:def is a valid identifier), the sugared slicing form only allows numeric literals. In order to construct slices that involve names and/or function calls, the form (: ...) can be used in an ncut expresion as an escape hatch to slice:

=> (setv abc:def -2)
=> (macroexpand '(ncut a abc:def (: (sum [1 2 3]) None abc:def)))
(get a (, abc:def (slice (sum [1 2 3]) None abc:def)))

Pandas allows extensive slicing along single or multiple axes:

=> (setv s1 (pd.Series (np.random.randn 6) :index (list "abcdef")))
=> s1
a    0.687645
b   -0.598732
c   -1.452075
d   -0.442050
e   -0.060392
f    0.440574
dtype: float64

=> (ncut s1 (: "c" None 2))
c   -1.452075
e   -0.060392
dtype: float64
=> (setv df (pd.DataFrame (np.random.randn 8 4)
                          :index (pd.date-range "1/1/2000" :periods 8)
                          :columns (list "ABCD")))
=> df
                   A         B         C         D
2000-01-01 -0.185291 -0.803559 -1.483985 -0.136509
2000-01-02 -3.290852 -0.688464  2.715168  0.750664
2000-01-03  0.771222 -1.170541 -1.015144  0.491510
2000-01-04  0.243287  0.769975  0.473460  0.407027
2000-01-05 -0.857291  2.395931 -0.950846  0.299086
2000-01-06 -0.195595  0.981791 -0.673646  0.637218
2000-01-07 -1.022636 -0.854971  0.603573 -1.169342
2000-01-08 -0.494866  0.783248 -0.064389 -0.960760

=> (ncut df.loc : ["B" "A"])
                   B         A
2000-01-01 -0.803559 -0.185291
2000-01-02 -0.688464 -3.290852
2000-01-03 -1.170541  0.771222
2000-01-04  0.769975  0.243287
2000-01-05  2.395931 -0.857291
2000-01-06  0.981791 -0.195595
2000-01-07 -0.854971 -1.022636
2000-01-08  0.783248 -0.494866

Note

For more info on the capabilities of multiindex slicing, check with the respective library.