Introduction to the Hy Language
The Hy programming language is a Lisp language that inter-operates smoothly with Python. We start with a few interactive examples that I encourage you to experiment with as you read. Then we will look at Hy data types and commonly used built-in functions that are used in the remainder of this book.
I assume that you know at least a little Python and more importantly the Python ecosystem and general tools like uv and pip.
Please start by installing uv on your laptop or server. Use either of the following commands on macOS or Linux:
1 brew install uv # macOS with Homebrew
2 curl -LsSf https://astral.sh/uv/install.sh | sh
On Windows use one of these commands:
1 irm https://astral.sh/uv/install.ps1 | iex
Whenever you start working in one of the book’s example directories, initialize the Python runtime environment for Hy and the libraries used in that example (uv run ... also does this automatically on first use):
1 uv sync
Using Python Libraries
Using Python libraries like google-genai, openai, ollama, TensorFlow, Keras, BeautifulSoup, etc. are the reason I use the Hy language. Importing Python code and libraries and calling out to Python is simple and here we look at sufficient examples so that you will understand example code that we will look at later.
Note: starting in August 2025 the example programs in the GitHub repository https://github.com/mark-watson/hy-lisp-python-book are in individual directories under source_code_for_examples, each pre-configured for use with uv.
For example, in the chapter Responsible Web Scraping we will use the BeautifulSoup library. We will look at some Python code snippets and the corresponding Hy language versions of these snippets. Let’s first look at a Python example that we will then convert to Hy:
1 from bs4 import BeautifulSoup
2
3 raw_data = '<html><body><a href="http://markwatson.com">Mark</a></body></html>'
4 soup = BeautifulSoup(raw_data)
5 a_tags = soup.find_all("a")
6 print("a tags:", a_tags)
In the following listing notice how we import other code and libraries in Hy. The special form setv is used to define variables in a local context. Since the setv statements in lines 4, 6, and 7 are used at the top level, they are global in the Python/Hy module named after the root name of the source file.
1 $ cd hy-lisp-python-book/source_code_for_examples/webscraping
2 $ uv run hy
3 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
4 => (import bs4 [BeautifulSoup])
5 => (setv raw-data "<html><body><a href=\"http://markwatson.com\">Mark</a></body></html>")
6 => (setv soup (BeautifulSoup raw-data "lxml"))
7 => (setv a (.find-all soup "a"))
8 => (print "atags:" a)
9 atags: [<a href="http://markwatson.com">Mark</a>]
10 => (type a)
11 <class 'bs4.element.ResultSet'>
12 => (dir a)
13 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort', 'source']
Notice in lines 3 and 6 that we can have “-” characters inside of variable and function names (raw-data and find-all in this case) in the Hy language where we might use “_” underscore characters in Python. Like Python, we can use type get get the type of a value and dir to see what symbols are available for a object.
Global vs. Local Variables
Although I don’t generally recommend it, sometimes it is convenient to export local variables defined with setv to be global variables in the context of the current module (that is defined by the current source file). As an example:
1 $ uv run hy
2 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
3 => (defn foo []
4 ... (global x)
5 ... (setv x 1)
6 ... (print x))
7 => (foo)
8 1
9 => x
10 1
11 =>
Before executing function foo the global variable x is undefined (unless you coincidentally already defined somewhere else). When function foo is called, a global variable x is defined and then it equal to the value 1.
Using Python Code in Hy Programs
If there is a Python source file, named for example, test.py in the same directory as a Hy language file:
1 def factorial (n):
2 if n < 2:
3 return 1
4 return n * factorial(n - 1)
This code will be in a module named test because that is the root source code file name. We might import the Python code using the following in Python:
1 import test
2
3 print(test.factorial(5))
and we can use the following in Hy to import the Python module test (defined in test.py):
1 (import test)
2
3 (print (test.factorial 5))
Running this interactively in Hy:
1 $ uv run hy
2 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
3 => (import test)
4 => test
5 <module 'test' from '/Users/markw/hy-experiments/test.py'>
6 => (print (test.factorial 5))
7 120
If we only wanted to import BeautifulSoup from the Python BeautifulSoup library bs4 we can specify this in the import form:
1 (import bs4 [BeautifulSoup])
Using Hy Libraries in Python Programs
There is nothing special about importing and using Hy library code or your own Hy scripts in Python programs. The directory hy-lisp-python-book/source_code_for_examples/use_hy_in_python in the git repository for this book https://github.com/mark-watson/hy-lisp-python-book contains an example Hy script get_web_page.hy that is a slightly modified version of code we will explain and use in the later chapter on web scraping and a short Python script use_hy_stuff.py that uses a function defined in Hy:
get_web_page.hy:
1 (import urllib.request [Request urlopen])
2
3 (setv default-headers {"User-Agent" "HyLangBook/1.0"})
4
5 (defn get-raw-data-from-web [uri [headers default-headers] [timeout 10]]
6 "Fetch URI and return the raw response body as bytes."
7 (with [response (urlopen (Request uri :headers headers) :timeout timeout)]
8 (.read response)))
9
10 (defn get-web-page-from-disk [file-path]
11 "Return the contents of a locally cached HTML file as a string."
12 (with [f (open file-path "r" :encoding "utf-8")]
13 (.read f)))
14
15 (defn main_hy []
16 (print (get-raw-data-from-web "https://markwatson.com")))
We define three functions here. Notice the optional arguments headers and timeout on line 5 where we provide default values in case the calling code does not provide them. The with form closes the HTTP response (and, in get-web-page-from-disk, the file) even if an error occurs. I named the last function main_hy with an underscore; a kebab-case name like main-hy would also work because Hy mangles it to main_hy for Python callers. In the next Python listing we import the Hy module after import hy (which installs Hy’s import hook) and call main_hy on line 4 using the Python calling syntax.
Hy is the same as Python once it is compiled to an abstract syntax tree (AST).
use_hy_in_python/use_hy_stuff.py:
1 import hy
2 from get_web_page import main_hy
3
4 main_hy()
What I want you to understand and develop a feeling for is that Hy and Python are really the same but with a different syntax and that both languages can easily be used side by side.
Replacing the Python slice (cut) Notation with the Hy Functional Form
In Python we use a special notation for extracting sub-sequences from lists or strings:
1 $ uv run python
2 Python 3.12.0 (main, Oct 2 2023, 20:56:14) [Clang 16.0.3 ] on darwin
3 Type "help", "copyright", "credits" or "license" for more information.
4 >>> s = '0123456789'
5 >>> s[2:4]
6 '23'
7 >>> s[-4:]
8 '6789'
9 >>> s[-4:-1]
10 '678'
11 >>>
In Hy this would be:
1 $ uv run hy
2 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
3 => (setv s "0123456789")
4 => (cut s 2 4)
5 '23'
6 => (cut s -4)
7 '6789'
8 => (cut s -4 -1)
9 '678'
10 =>
It also works to use cut with setv to destructively change a list; for example:
1 => (setv x [0 1 2 3 4 5 6 7 8])
2 => x
3 [0, 1, 2, 3, 4, 5, 6, 7, 8]
4 => (cut x 2 4)
5 [2, 3]
6 => (setv (cut x 2 4) [22 33])
7 => x
8 [0, 1, 22, 33, 4, 5, 6, 7, 8]
Iterating Through a List With Index of Each Element
We will use lfor as a form of Python list comprehension; for example:
1 => (setv sentence "The ball rolled")
2 => (lfor i (enumerate sentence) i)
3 [(0, 'T'), (1, 'h'), (2, 'e'), (3, ' '), (4, 'b'), (5, 'a'), (6, 'l'), (7, 'l'), (8, ' '), (9, 'r'), (10, 'o'), (11, 'l'), (12, 'l'), (13, 'e'), (14, 'd')]
4 => (setv vv (lfor i (enumerate sentence) i))
5 => vv
6 [(0, 'T'), (1, 'h'), (2, 'e'), (3, ' '), (4, 'b'), (5, 'a'), (6, 'l'), (7, 'l'), (8, ' '), (9, 'r'), (10, 'o'), (11, 'l'), (12, 'l'), (13, 'e'), (14, 'd')]
7 => (for [[a b] vv]
8 ... (print a b))
9 0 T
10 1 h
11 2 e
12 3
13 4 b
14 5 a
15 6 l
16 7 l
17 8
18 9 r
19 10 o
20 11 l
21 12 l
22 13 e
23 14 d
24 =>
On line 2, the expression (enumerate sentence) generates one character at a time from a string. enumerate operating on a list will generate one list element at a time.
Line 9 shows an example of destructuring: the values in the list vv are tuples (tuples are like lists but are immutable, that is, once a tuple is constructed the values it holds can not be changed) with two values. The values in each tuple are copied into binding variables in the list [a b]. We could have used the following code instead but it is more verbose:
1 => (for [x vv]
2 (setv a (first x))
3 (setv b (second x))
4 ... (print a b))
5 0 T
6 1 h
7 2 e
8 3
9 4 b
10 . . .
11 13 e
12 14 d
13 =>
Formatted Output
I suggest using the Python format method when you need to format output. In the following repl listing, you can see a few formatting options: insert any Hy data into a string (line 3), print values with a specific width and right justified (in line 5 the width for both values is 15 characters), print values with a specific width and left justified (in line 7), and limiting the number of characters values can be expressed as (in line 9 the object “cat” is expressed as just the first two characters and the value 3.14159 is expressed as just three numbers, the period not counting).
1 $ uv run hy
2 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
3 => (.format "first: {} second: {}" "cat" 3.14159)
4 'first: cat second: 3.14159'
5 => (.format "first: {:>15} second: {:>15}" "cat" 3.14159)
6 'first: cat second: 3.14159'
7 => (.format "first: {:15} second: {:15}" "cat" 3.14159)
8 'first: cat second: 3.14159'
9 => (.format "first: {:.2} second: {:.3}" "cat" 3.14159)
10 'first: ca second: 3.14'
11 =>
Notice the calling .format here returns a string value rather than writing to an output stream.
Importing Libraries from Different Directories on Your Laptop
I usually write applications by first implementing simpler low-level utility libraries that are often not in the same directory path as the application that I am working on. Let’s look at a simple example of accessing the library nlp_lib.hy in the directory source_code_for_examples/nlp from the directory source_code_for_examples/webscraping. Because each example directory has its own virtual environment, I use uv run --with to add spacy and its small English model to the webscraping environment for this one session:
1 $ cd hy-lisp-python-book/source_code_for_examples/webscraping
2 $ uv run --with spacy --with "en_core_web_sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl" hy
3 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
4 => (import sys)
5 => (sys.path.insert 1 "../nlp")
6 => (import nlp-lib [nlp])
7 => (setv result (nlp "President George Bush went to Mexico and he had a very good meal"))
8 => (get result "entities")
9 [['George Bush', 'PERSON'], ['Mexico', 'GPE']]
10 =>
Here I did not package and install the library nlp_lib.hy. I rely on relative paths between the library directory and the application code that uses the library.
On line 5 I am inserting the library directory into the Python system load path so the import statement on line 6 can find the nlp-lib library. For anything beyond quick experiments, packaging a shared library and adding it as a dependency is more robust; we do that in the chapter Hy Tooling, Packaging, REPL, and Types.
Hy Looks Like Clojure: How Similar Are They?
Clojure is a dynamic general purpose Lisp language for the JVM. One of the great Clojure features is support of immutable data (read only after creation) that makes multi-threaded code easier to write and maintain.
Unfortunately, Clojure’s immutable data structures cannot be easily implemented efficiently in Python so the Hy language does not support immutable data, except for tuples. Otherwise the syntax for defining functions, using maps/hash tables/dictionaries, etc. is similar between the two languages.
The original Hy language developer Paul Tagliamonte was clearly inspired by Clojure.
The book Serious Python by Julien Danjou has an entire chapter (Chapter 9) on the Python AST (abstract syntax tree), an introduction to Hy, and an interview with Paul Tagliamonte. Recommended!
This podcast in 2015 interviews Hy developers Paul Tagliamonte, Tuukka Turto, and Morten Linderud. You can see the current Hy contributor list on github.
Plotting Data Using the Numpy and the Matplotlib Libraries
Data visualization is a common task when working with numeric data. In a later chapter on Deep Learning we will use two functions, the relu and sigmoid functions. Here we will use a few simple Hy language scripts to plot these functions.
The Numpy library supports what is called “broadcasting” in Python. In the function sigmoid that we define in the following REPL, we can pass either a single floating point number or a Numpy array as an argument. When we pass a Numpy array, then the function sigmoid is applied to each element of the Numpy array:
1 $ uv run hy
2 Hy 1.3.1 (Eyes in the Sky) using CPython(main) 3.14.7 on Darwin
3 => (import numpy :as np)
4 => (import matplotlib.pyplot :as plt)
5 =>
6 => (defn sigmoid [x]
7 ... (/ 1.0 (+ 1.0 (np.exp (- x)))))
8 => (sigmoid 0.2)
9 0.549833997312478
10 => (sigmoid 2)
11 0.8807970779778823
12 => (np.array [-5 -2 0 2 5])
13 array([-5, -2, 0, 2, 5])
14 => (sigmoid (np.array [-5 -2 0 2 5]))
15 array([0.00669285, 0.11920292, 0.5, 0.88079708, 0.99330715])
16 =>
The git repository directory source_code_for_examples/matplotlib_examples contains two similar scripts (plot_sigmoid.hy and plot_relu.hy) for plotting the sigmoid and relu functions. Here is the script to plot the sigmoid function:
1 (import numpy :as np)
2 (import matplotlib.pyplot :as plt)
3
4 (defn sigmoid [x]
5 (/ 1.0 (+ 1.0 (np.exp (- x)))))
6
7 (setv X (np.linspace -8 8 50))
8 (plt.plot X (sigmoid X))
9 (plt.title "Sigmoid Function")
10 (plt.ylabel "Sigmoid")
11 (plt.xlabel "X")
12 (plt.grid)
13 (plt.show)
The generated plot looks like this on macOS (Matplotlib is portable and also works on Windows and Linux):
Bonus Points: Configuration for macOS and iTerm2 for Generating Plots Inline in a Hy REPL and Shell
On the macOS iTerm2 terminal app and on most Linux terminal apps, it is possible to get inline matplotlib plots in a shell (bash, zsh, etc.), in Emacs, etc. This will take some setup work but it is well worth it especially if you work on remote servers via SSH or tmux. Here is the setup for macOS:
1 uv add itermplot # or: uv tool install itermplot
The add the following to your .profile, .bash_profile, or .zshrc (depending on your shell setup):
1 export MPLBACKEND="module://itermplot"
Here we run an example from the last section in a zsh shell (bash, etc. also should work):
The best part of generating inline plots is during interactive REPL-based coding sessions:
If you use a Mac laptop to SSH into a remote Linux server you need to install itermplot and set the environment variable MPLBACKEND on the remote server.
Modern Hy and Python 3.12–3.15: What Changed Since Hy 1.1
When I started earlier editions of this book, Hy 0.x and 1.1 were the targets. Every project in this repository now pins hy>=1.3.1 and uses uv for reproducible environments. This section walks through the language features added across Hy 1.2 and Hy 1.3 and shows how Hy tracks modern Python (3.12 through 3.15) without giving up portability.
The companion code for this section is in the directory source_code_for_examples/modern_hy, in addition to the interop example in source_code_for_examples/use_hy_in_python.
Version Policy and Upgrade Workflow
Hy 1.3.1 supports CPython 3.9 through 3.15. In this book our project pyproject.toml files require Python 3.12 or newer (requires-python = ">=3.12"), and I test the examples on Python 3.12 and 3.14. When a feature requires Python 3.14 or 3.15 (such as PEP 750 template strings or PEP 810 lazy imports), I call it out explicitly so you can keep your main codebase portable across Python 3.12+.
When upgrading an older Hy 1.1 project to 1.3.1, my workflow has four steps:
- Pin
hy>=1.3.1inpyproject.tomland runuv sync. - Run
uv run hy2py your_module.hyon each file to inspect the Python code that Hy generates. - Run your interactive sessions with
uv run hy --spywhen you want to see the translated Python statement before each form executes. - Run
uv run pytestto verify behavior across your test suite.
Assignment: setv :chain, setx, let, and nonlocal
Hy 1.2 added :chain to setv so you can initialize multiple targets to the same value—just like Python’s hits = misses = errors = 0:
1 (defn reset-counters []
2 "Return a dictionary of zeroed counters using (setv :chain ...)."
3 (setv :chain [hits misses errors] 0)
4 {"hits" hits "misses" misses "errors" errors})
Whereas setv is a statement form (or compiles to assignments), setx is Python’s assignment expression (:=, the walrus operator). It binds a name and returns the value inside a condition or comprehension, avoiding a redundant function call:
1 (defn first-non-empty [#^ (get list str) lines]
2 "Demonstrate (setx ...) inside a condition and a comprehension."
3 (setv cleaned
4 (lfor raw lines
5 :if (setx stripped (.strip raw))
6 stripped))
7 (if cleaned (get cleaned 0) ""))
For lexical scoping inside a function, let creates bindings that exist only within the let body, while nonlocal lets an inner closure mutate a variable from an enclosing function scope:
1 (defn make-accumulator [#^ int start]
2 "Return a closure that increments an internal total using nonlocal."
3 (let [initial (max 0 start)]
4 (setv total initial)
5 (defn step [#^ int delta]
6 (nonlocal total)
7 (+= total delta)
8 total)
9 step))
Structural Pattern Matching with match
Python’s structural pattern matching (match/case) is expressed in Hy as (match subject pattern-1 result-1 pattern-2 result-2 ...). Each arm pairs a pattern (plus an optional :if guard) with a result expression, and because match is an expression in Hy, it returns the value of the matching arm.
Hy 1.3 improved match so patterns work cleanly with dataclasses, sequences, OR patterns (|), :as bindings, and even Hy’s own syntax models (hy.models.Expression, hy.models.Symbol):
1 (defclass [dataclass] QueryEvent []
2 #^ str kind
3 #^ object payload)
4
5 (defn #^ str describe-event [#^ object event]
6 "Describe a domain event or a raw Hy model using structural pattern matching."
7 (match event
8 (QueryEvent :kind "lookup" :payload (| "isa" "part_of") :as pred)
9 f"hierarchy lookup on {pred}"
10 (QueryEvent :kind "lookup" :payload pred)
11 f"lookup on {pred}"
12 (QueryEvent :kind "limit" :payload (int n)) :if (> n 0)
13 f"limit to {n} triples"
14 (hy.models.Expression [(hy.models.Symbol "edge") subj obj pred])
15 f"model edge: {(str subj)} -{(str pred)}-> {(str obj)}"
16 [subj obj pred]
17 f"tuple edge: {subj} -{pred}-> {obj}"
18 _
19 "unknown event"))
Matching directly on hy.models.Expression is especially useful when you write macros or small domain-specific languages, which we will do in the next chapter.
Type Annotations (#^), deftype, and Type-Checking via hy2py
Hy attaches type annotations with the #^ reader macro before a variable, parameter, or function name. For Python 3.12+ type aliases (PEP 695), Hy provides deftype, including generic type parameters via :tp:
1 (deftype NodeId str)
2 (deftype Triple (get tuple #(NodeId str NodeId)))
3 (deftype :tp [T] Pair (get tuple #(T T)))
4
5 (defn #^ (get Pair NodeId) endpoints [#^ Triple triple]
6 "Return the (subject, object) pair of a (subject, object, predicate) triple."
7 (setv [subj obj _] triple)
8 #(subj obj))
Static type checkers such as mypy and pyright read Python syntax rather than .hy files, so the standard workflow is to translate your .hy module with hy2py and pass the generated Python to the checker. We will automate that pipeline in the tooling chapter.
Strings: Bracket Strings and Python 3.14 Template Strings (t"...")
When you embed multi-line SPARQL, Cypher, SQL, or prompts in Hy code, bracket strings #[delim[...]delim] avoid backslash-escaping altogether:
1 (setv CYPHER-SAMPLE #[cypher[
2 MATCH (s:Concept)-[r]->(o:Concept)
3 WHERE r.predicate = "isa"
4 RETURN s.id, o.id
5 ]cypher])
Requires Python 3.14+ and Hy 1.3+: Python 3.14 introduced PEP 750 template strings (
t"..."), and Hy 1.3 supports them directly. Unlike an f-stringf"...", which immediately evaluates to astr, a t-stringt"SELECT ... WHERE pred = {predicate}"evaluates to astring.templatelib.Templateobject whose.stringsand.interpolationscan be inspected and sanitized before rendering—ideal for SQL, SPARQL, or HTML escaping.
Modern Comprehensions, Async Forms, and Python 3.14/3.15 Runtime Notes
Hy 1.3 also supports PEP 798 unpacking inside comprehensions: using #* in the result position of lfor, sfor, or gfor splices each inner iterable into the output:
1 (defn #^ (get list str) flatten-batches [#^ (get list (get list str)) batches]
2 "Flatten a list of batches with #* inside lfor (PEP 798 in Hy 1.3)."
3 (lfor batch batches #* batch))
Modern Hy provides full syntax for asynchronous Python—(defn :async ...), (fn :async ...), (with [:async ...] ...), and (for [:async ...] ...)—which we cover in depth in the Async and Concurrent Hy chapter. And when running on Python 3.14’s free-threaded build or Python 3.15’s lazy imports (pragma), pure Hy functions compile to standard Python bytecode and follow the exact same concurrency and import semantics as regular Python modules.
Mini-Project: Refactoring the UMLS Triple Processor to Modern Hy
To see these features working together, source_code_for_examples/modern_hy/umls_modern.hy refactors the triple-parsing and summarization core of plots_with_graphviz/UMLS_graph.hy using deftype, #^ annotations, setv :chain, setx, match, and #* comprehension unpacking:
1 (import dataclasses [dataclass])
2
3 (deftype NodeId str)
4 (deftype Predicate str)
5 (deftype Triple (get tuple #(NodeId NodeId Predicate)))
6
7 (setv PREDICATE-COLORS
8 {"isa" "#FF6B6B"
9 "interacts_with" "#4ECDC4"
10 "affects" "#45B7D1"
11 "causes" "#96CEB4"
12 "part_of" "#FFEAA7"
13 "location_of" "#DDA0DD"
14 "treats" "#98D8C8"})
15
16 (defclass [dataclass] GraphSummary []
17 #^ int triple-count
18 #^ int node-count
19 #^ (get dict #(Predicate int)) predicate-counts)
20
21 (defn #^ str predicate-color [#^ Predicate pred]
22 "Return the color hex string for a predicate using structural match."
23 (match pred
24 (| "isa" "part_of") (.get PREDICATE-COLORS pred "#CCCCCC")
25 (str p) :if (in p PREDICATE-COLORS) (get PREDICATE-COLORS p)
26 _ "#CCCCCC"))
27
28 (defn #^ (get list Triple) parse-triple-lines [
29 #^ (get list str) lines
30 #^ (| int None) [limit None]
31 #^ (| Predicate None) [filter-pred None]]
32 "Parse whitespace-separated (subject object predicate) lines."
33 (setv triples
34 (lfor line lines
35 :if (setx stripped (.strip line))
36 :if (not (.startswith stripped "#"))
37 :setv tokens (.split stripped)
38 :if (= (len tokens) 3)
39 :setv [subj obj pred] tokens
40 :if (or (is filter-pred None) (= pred filter-pred))
41 #(subj obj pred)))
42 (if (is limit None)
43 triples
44 (cut triples 0 limit)))
45
46 (defn #^ GraphSummary summarize-triples [#^ (get list Triple) triples]
47 "Compute node and predicate counts for a list of triples."
48 (setv :chain [triple-count node-count] 0)
49 (setv endpoints (lfor [s o _] triples #* [s o]))
50 (setv unique-nodes (set endpoints))
51 (setv #^ (get dict #(Predicate int)) counts {})
52 (for [[_ _ pred] triples]
53 (setv (get counts pred) (+ (.get counts pred 0) 1)))
54 (setv triple-count (len triples)
55 node-count (len unique-nodes))
56 (GraphSummary
57 :triple-count triple-count
58 :node-count node-count
59 :predicate-counts counts))
You can run the demo, the test suite, and the hy2py + mypy check from source_code_for_examples/modern_hy:
1 $ cd source_code_for_examples/modern_hy
2 $ uv sync
3 $ uv run hy demo.hy
4 === Modern Hy 1.3.1 Tour ===
5 Python: 3.14.7
6 Counters: {'hits': 0, 'misses': 0, 'errors': 0}
7 First non-empty: hello hy 1.3
8 Accumulator steps: 15 22
9 Endpoints: ('aspirin', 'headache')
10 Match: hierarchy lookup on isa
11 Match: limit to 25 triples
12 Match: model edge: aspirin -treats-> headache
13 Match: tuple edge: cell -has_part-> nucleus
14 Safe query: ('SELECT subj, obj FROM triples WHERE pred = ? LIMIT ?', ('isa', 10))
15 Flattened batches: ['a', 'b', 'c', 'd', 'e']
16 UMLS summary: GraphSummary(triple_count=4, node_count=6, predicate_counts={'treats': 2, 'isa': 1, 'affects': 1})
17 Color for 'isa': #FF6B6B
18 $ uv run pytest -q
19 ....... [100%]
20 7 passed in 0.08s
21 $ uv run hy2py umls_modern.hy > /tmp/umls_modern.py
22 $ uv run mypy --ignore-missing-imports /tmp/umls_modern.py
23 Success: no issues found in 1 source file
Optional Practice Problems
To solidify your understanding of data visualization and Python-Hy interoperability, try completing the following exercises:
Data Visualization and Plotting
- Plotting Multiple Curves: Modify
plot_sigmoid.hy(or create a new Hy script) to plot both the Sigmoid and ReLU functions on the same graph. Use(plt.plot ... :label "Sigmoid")and(plt.plot ... :label "ReLU"), and call(plt.legend)to render a legend. -
Visual Reference Lines: Add a horizontal dotted line at
on your Sigmoid plot to indicate the inflection point, and a vertical line at
. In Matplotlib, this can be done using:
1 (plt.axhline :y 0.5 :color "red" :linestyle "--") 2 (plt.axvline :x 0.0 :color "gray" :linestyle "-.")
- Plotting Tanh: Implement and plot the hyperbolic tangent activation function (
). The equation is
. Hint: you can use numpy’s built-in (np.tanh x). Compare its output range with the Sigmoid function.
Python Interoperability
- Passing Parameters Across Languages: Modify
get_web_page.hyanduse_hy_stuff.pyso that instead of scraping a hardcoded URL, the Python script takes a URL as input from the user (or via command line usingsys.argv) and passes it as an argument to the Hy function. - Overriding Default Parameters: The function
get-raw-data-from-webinget_web_page.hydefines an optional argumentheaderswith a default dictionary value. Write Python code inuse_hy_stuff.pyto callget_raw_data_from_webdirectly, overriding the user agent to{"User-Agent": "Custom-Agent-Python"}. (Recall that kebab-case Hy names map to snake_case Python names, soget-raw-data-from-webbecomesget_raw_data_from_web.) - Handling Interoperable Exceptions: Wrap the network request in
use_hy_stuff.pywith Python’s standardtry...exceptexception handling block. Catchurllib.error.URLErrorto handle connection failures gracefully when an invalid URL is passed, demonstrating how exceptions flow seamlessly between Hy and Python.