Hy Tooling, Packaging, REPL, and Types
Running a single .hy script is easy. Turning that script into an installable library that both Hy and Python projects can import, test with pytest, type-check with mypy, and test in continuous integration takes a few specific rules. Every example in this book uses uv, pyproject.toml, and pytest, and in this chapter I show you how all of the pieces fit together.
The code for this chapter is in the directory source_code_for_examples/hy_kg_utils.
What You Will Build
We will build and package hy-kg-utils, an installable Hy library using the standard src/ layout. It exports:
- A typed class
GraphClientthat stores(subject, predicate, object)triples in memory and imports or exports tab-separated (TSV) files. - A typed function
query->rows(and its Python aliasquery_to_rows) that queries aGraphClientand returns sorted dictionary rows. - A hygienic macro
with-graphthat creates a temporaryGraphClient, optionally loads seed triples, runs a body of forms, and closes the client inside afinallyblock.
Along with the package itself, the project includes a pytest suite written in Hy and Python, an interactive HYSTARTUP file, a scripts/typecheck.sh pipeline that translates .hy to .py with hy2py and runs mypy --strict, and a GitHub Actions workflow.
1 +-----------------------+ hy2py +-------------------------+
2 | src/hy_kg_utils/*.hy | -----------------> | build/typecheck/*.py |
3 | (core.hy, macros.hy) | | (checked by mypy) |
4 +-----------+-----------+ +-------------------------+
5 |
6 | imported via src/hy_kg_utils/__init__.py (starts with `import hy`)
7 v
8 +-----------+-----------+--------------------+-------------------------+
9 | | | |
10 v v v v
11 Hy callers Python callers pytest suite uv build
12 (import + require) (import hy_kg_utils) (test_*.hy + test_*.py) (.whl + .tar.gz)
Why It Matters
Hy compiles directly to Python abstract syntax trees (ASTs), so it shares Python’s runtime and package ecosystem. Still, three practical differences trip up developers who package a Hy project for the first time:
- Python’s import machinery does not recognize
.hyfiles untilimport hyhas executed at least once in the process. - Build backends such as Hatchling or Setuptools may omit
.hyfiles from wheels unless you configure package inclusion rules. - Static type checkers (
mypy,pyright) read Python syntax, not S-expressions, so type-checking Hy requires translating.hymodules to Python withhy2pyfirst.
Once you solve these three details in a reusable project template, developing a library in Hy is as fast and repeatable as developing one in pure Python.
The Hy Angle
In Python, resource cleanup requires writing a context manager class with __enter__ and __exit__ methods or decorating a generator with @contextlib.contextmanager. In Hy, we can ship classes and functions for Python and Hy callers while also exporting compile-time macros like with-graph for Hy callers. Better yet, by referencing hy.I.hy_kg_utils.core.GraphClient inside the macro expansion, with-graph resolves GraphClient automatically without forcing the caller to import GraphClient into their own namespace.
Python Equivalent
Here is how a caller uses hy-kg-utils in Hy with the with-graph macro versus the equivalent code in plain Python:
1 ;; Hy caller
2 (require hy_kg_utils [with-graph])
3 (import hy_kg_utils.core [query->rows])
4
5 (setv rows
6 (with-graph [g [#("hy" "is-a" "lisp")]]
7 (query->rows g :s "hy")))
1 # Python caller
2 from hy_kg_utils import GraphClient, query_to_rows
3
4 g = GraphClient()
5 try:
6 g.add_many([("hy", "is-a", "lisp")])
7 rows = query_to_rows(g, s="hy")
8 finally:
9 g.close()
Both snippets execute the same underlying bytecode and return the same list of dictionaries.
Run It
No external services or API keys are required. As of this edition (November 2026), we use uv with Python 3.12 through 3.14 and Hy 1.3.1.
Change into source_code_for_examples/hy_kg_utils, install the environment, and run the Hy demo, the Python caller script, the test suite, and the type-checking script:
1 cd source_code_for_examples/hy_kg_utils
2 uv sync
3 uv run hy examples/demo.hy
4 uv run python examples/python_caller.py
5 uv run pytest -v
6 bash scripts/typecheck.sh
Here is the actual output from uv run hy examples/demo.hy:
1 === 1. Using with-graph macro and query->rows from Hy ===
2 Graph 'default' has 5 triples; predicates: ['builds', 'checks', 'compiles-to', 'is-a', 'supports']
3 {'subject': 'hy', 'predicate': 'compiles-to', 'object': 'python-ast'}
4 {'subject': 'hy', 'predicate': 'is-a', 'object': 'lisp'}
5 {'subject': 'hy', 'predicate': 'supports', 'object': 'macros'}
6 After with-graph block, g.closed = True
7
8 === 2. Inspecting macro expansion and name mangling ===
9 mangle('query->rows') -> hyx_query_XgreaterHthan_signXrows
10 unmangle(mangled) -> query->rows
11 mangle('query-to-rows') -> query_to_rows
12 macroexpand-1 of (with-graph [g] (.count g)):
13 '(do (setv g (hy.I.hy_kg_utils.core.GraphClient)) (try (setv _hy_gensym_seed_2 []) (when _hy_gensym_seed_2 (.add-many g (list _hy_gensym_seed_2))) (.count g) (finally (.close g))))
Here is the output from uv run python examples/python_caller.py:
1 === Calling hy_kg_utils from plain Python ===
2 hy_kg_utils --[exposes]--> GraphClient
3 hy_kg_utils --[exposes]--> query_to_rows
4 python --[imports]--> hy_kg_utils
5 Client closed: True
6
7 === Evaluating a Hy macro from Python via hy.eval ===
8 [{'subject': 'hy.eval', 'predicate': 'runs', 'object': 'with-graph'}]
Here is the output from uv run pytest -v:
1 ============================= test session starts ==============================
2 platform darwin -- Python 3.14.7, pytest-9.2.0, pluggy-1.7.0
3 cachedir: .pytest_cache
4 rootdir: /Users/markw/GITHUB/hy-lisp-python-book/source_code_for_examples/hy_kg_utils
5 configfile: pyproject.toml
6 testpaths: tests
7 collecting ... collected 11 items
8
9 tests/test_hy_kg_utils.hy::test_fixture_and_predicates PASSED [ 9%]
10 tests/test_hy_kg_utils.hy::test_query_to_rows_parametrized[hy-None-None-2] PASSED [ 18%]
11 tests/test_hy_kg_utils.hy::test_query_to_rows_parametrized[None-is-a-lisp-1] PASSED [ 27%]
12 tests/test_hy_kg_utils.hy::test_query_to_rows_parametrized[uv-manages-None-1] PASSED [ 36%]
13 tests/test_hy_kg_utils.hy::test_query_to_rows_parametrized[unknown-None-None-0] PASSED [ 45%]
14 tests/test_hy_kg_utils.hy::test_raises_on_empty_term_and_closed_client PASSED [ 54%]
15 tests/test_hy_kg_utils.hy::test_monkeypatch_default_graph_name PASSED [ 63%]
16 tests/test_hy_kg_utils.hy::test_tmp_path_tsv_roundtrip PASSED [ 72%]
17 tests/test_hy_kg_utils.hy::test_with_graph_macro_closes_on_exit PASSED [ 81%]
18 tests/test_python_interop.py::test_python_imports_hy_package PASSED [ 90%]
19 tests/test_python_interop.py::test_hy_name_mangling_and_eval PASSED [100%]
20
21 ============================== 11 passed in 0.09s ==============================
And here is the output from bash scripts/typecheck.sh:
1 === Translated Python modules in build/typecheck/hy_kg_utils ===
2 __init__.py
3 core.py
4 macros.py
5 === Running mypy on translated core.py and __init__.py ===
6 Success: no issues found in 2 source files
1. The 10-Minute uv Workflow
Throughout this book, every project uses uv to manage Python versions, virtual environments, lockfiles, and package builds. As of this edition (November 2026), creating a new Hy project from scratch takes four commands:
1 uv init --package my-hy-pkg
2 cd my-hy-pkg
3 uv add "hy>=1.3.1"
4 uv add --dev "pytest>=9.2.0" "mypy>=1.18"
Key uv commands you will use daily with Hy:
uv sync: Creates.venv, resolves dependencies, writesuv.lock, and installs the current package in editable mode.uv run hy: Launches the Hy REPL inside the project environment.uv run hy path/to/script.hy: Runs a Hy script.uv run pytest: Runs tests across both.pyand.hyfiles (onceconftest.pyis present).uv build: Builds a source distribution (.tar.gz) and wheel (.whl) indist/.
Committing uv.lock to version control ensures that every machine and CI runner installs the exact same versions of hy, funcparserlib, and test dependencies.
2. Project Layout: Scripts vs. Libraries
For a standalone script or demo, placing .hy files in the project root next to pyproject.toml is fine. For a reusable library, use the src/ layout:
1 hy_kg_utils/
2 ├── .github/
3 │ └── workflows/
4 │ └── ci.yml
5 ├── conftest.py
6 ├── examples/
7 │ ├── demo.hy
8 │ ├── hystartup.hy
9 │ └── python_caller.py
10 ├── pyproject.toml
11 ├── scripts/
12 │ └── typecheck.sh
13 ├── src/
14 │ └── hy_kg_utils/
15 │ ├── __init__.py
16 │ ├── core.hy
17 │ └── macros.hy
18 └── tests/
19 ├── test_hy_kg_utils.hy
20 └── test_python_interop.py
The src/ layout prevents pytest or Python from accidentally importing un-packaged local files from the working directory instead of the installed package in .venv.
Notice that the package entry point is src/hy_kg_utils/__init__.py, a .py file, not __init__.hy. When a Python program runs import hy_kg_utils, Python has not necessarily imported hy yet. If the package only had __init__.hy, Python’s default import machinery would ignore it and fail with ModuleNotFoundError. Starting __init__.py with import hy registers Hy’s import hook before importing the .hy submodules:
1 """hy_kg_utils: tiny knowledge-graph helpers written in Hy."""
2
3 import hy # register the .hy import hook before importing Hy modules
4
5 from hy_kg_utils.core import GraphClient, MaybeStr, Row, Triple, query_to_rows
6
7 hy.macros.require("hy_kg_utils.macros", None, assignments="EXPORTS")
8
9 __version__ = "0.1.0"
10 __all__ = ["GraphClient", "MaybeStr", "Row", "Triple", "query_to_rows", "__version__"]
That call to hy.macros.require("hy_kg_utils.macros", None, assignments="EXPORTS") attaches the exported macros from hy_kg_utils.macros onto the top-level hy_kg_utils module as well, so Hy users can write either (require hy_kg_utils [with-graph]) or (require hy_kg_utils.macros [with-graph]).
3. Interop Between Hy and Python
Hy and Python share the same runtime objects, classes, and modules. You have four primary interop tools when crossing the boundary:
- Importing Python into Hy: Use
(import pathlib [Path])orhy.I(for example(hy.I.math.sqrt 16)).hy.Iimports on demand without binding a name in the current scope, which makes it ideal inside macros. - Importing Hy into Python: Import the package after
import hy(or import a package whose__init__.pystarts withimport hy). - Identifier mangling (
hy.mangleandhy.unmangle): Hy converts Lisp names into valid Python identifiers. Single dashes become underscores (add-manybecomesadd_many), while punctuation characters use ahyx_prefix and Unicode character names:
1 (hy.mangle "add-many") ; => "add_many"
2 (hy.mangle "query->rows") ; => "hyx_query_XgreaterHthan_signXrows"
3 (hy.unmangle "hyx_query_XgreaterHthan_signXrows") ; => "query->rows"
Because query->rows mangles to hyx_query_XgreaterHthan_signXrows, we define a friendly alias (setv query-to-rows query->rows) in core.hy so Python callers can import query_to_rows.
- Evaluating Hy from Python (
hy.read_manyandhy.eval): Python code cannot expand a Hy macro directly with Python syntax, but it can parse and evaluate S-expressions at runtime:
1 import hy
2
3 forms = hy.read_many(
4 "(do (require hy_kg_utils [with-graph])"
5 " (import hy_kg_utils.core [query->rows])"
6 ' (with-graph [g [#("hy.eval" "runs" "with-graph")]]'
7 " (query->rows g)))"
8 )
9 result = hy.eval(forms)
Similarly, inside Hy, hy.R lets you call a macro without importing it at the top of the file: (hy.R.hy_kg_utils.macros.with-graph [g] (.count g)).
4. Packaging a Hy Library (pyproject.toml and Wheels)
Here is source_code_for_examples/hy_kg_utils/pyproject.toml:
1 [project]
2 name = "hy-kg-utils"
3 version = "0.1.0"
4 description = "Tiny knowledge-graph helpers written in Hy: a function, a class, and a macro, packaged as a wheel."
5 readme = "README.md"
6 requires-python = ">=3.12"
7 license = "Apache-2.0"
8 authors = [{ name = "Mark Watson" }]
9 keywords = ["hy", "lisp", "knowledge-graph", "triples"]
10 classifiers = [
11 "Programming Language :: Hy",
12 "Programming Language :: Python :: 3",
13 "Programming Language :: Python :: 3.12",
14 "Programming Language :: Python :: 3.13",
15 "Programming Language :: Python :: 3.14",
16 "Topic :: Software Development :: Libraries",
17 ]
18 dependencies = ["hy>=1.3.1"]
19
20 [project.optional-dependencies]
21 typecheck = ["mypy>=1.18"]
22
23 [dependency-groups]
24 dev = ["pytest>=9.2.0", "mypy>=1.18"]
25
26 [build-system]
27 requires = ["hatchling>=1.27"]
28 build-backend = "hatchling.build"
29
30 [tool.hatch.build.targets.wheel]
31 packages = ["src/hy_kg_utils"]
32 # Hatchling only picks up files git would track; be explicit so .hy
33 # sources always land in the wheel next to __init__.py.
34 include = ["src/hy_kg_utils/*.py", "src/hy_kg_utils/*.hy"]
35
36 [tool.hatch.build.targets.sdist]
37 include = ["src", "tests", "examples", "scripts", "conftest.py", "README.md"]
38
39 [tool.pytest.ini_options]
40 testpaths = ["tests"]
41
42 [tool.mypy]
43 strict = true
44
45 [[tool.mypy.overrides]]
46 module = ["hy", "hy.*"]
47 ignore_missing_imports = true
48
49 [tool.uv]
50 exclude-newer = "2 days"
Pay attention to three packaging details:
- Classifier: Include
"Programming Language :: Hy"inclassifiersso PyPI indexes your package under Hy packages. - Explicit
.hyinclusion: In[tool.hatch.build.targets.wheel], specifyinclude = ["src/hy_kg_utils/*.py", "src/hy_kg_utils/*.hy"]. When a user installs the wheel, Hy compiles the.hyfiles to bytecode on import. - Exporting objects and macros: In
src/hy_kg_utils/macros.hy, we use(export :objects [] :macros [with-graph])to populate__all__and_hy_export_macros:
1 "Compile-time macros for hy_kg_utils."
2
3
4 (defmacro with-graph [binding #* body]
5 "Bind a fresh GraphClient (with optional seed triples) and close it on exit.
6
7 Usage:
8 (with-graph [g]
9 (.add g \"hy\" \"is-a\" \"lisp\"))
10
11 (with-graph [g [#(\"hy\" \"is-a\" \"lisp\")]]
12 (query->rows g :s \"hy\"))"
13 (when (or (not (isinstance binding hy.models.Sequence))
14 (< (len binding) 1)
15 (> (len binding) 2))
16 (raise (SyntaxError
17 "with-graph expects [client-sym] or [client-sym seed-triples]")))
18 (setv client-sym (get binding 0))
19 (setv seed-expr (if (= (len binding) 2) (get binding 1) '[]))
20 (setv seed-var (hy.gensym "seed"))
21 `(do
22 (setv ~client-sym (hy.I.hy_kg_utils.core.GraphClient))
23 (try
24 (setv ~seed-var ~seed-expr)
25 (when ~seed-var
26 (.add-many ~client-sym (list ~seed-var)))
27 ~@body
28 (finally
29 (.close ~client-sym)))))
30
31
32 (export
33 :objects []
34 :macros [with-graph])
Notice how with-graph uses (hy.gensym "seed") so seed-expr is evaluated at most once without risking variable capture in the caller’s body.
Building and Verifying the Wheel in a Clean Environment
Let’s build the wheel with uv build, inspect its contents, and install it into an isolated temporary virtual environment to verify that all .hy files were packaged properly:
1 uv build
2 unzip -l dist/hy_kg_utils-0.1.0-py3-none-any.whl
Output:
1 Building source distribution...
2 Building wheel from source distribution...
3 Successfully built dist/hy_kg_utils-0.1.0.tar.gz
4 Successfully built dist/hy_kg_utils-0.1.0-py3-none-any.whl
5 Archive: dist/hy_kg_utils-0.1.0-py3-none-any.whl
6 Length Date Time Name
7 --------- ---------- ----- ----
8 394 02-02-2020 00:00 hy_kg_utils/__init__.py
9 3997 02-02-2020 00:00 hy_kg_utils/core.hy
10 976 02-02-2020 00:00 hy_kg_utils/macros.hy
11 3244 02-02-2020 00:00 hy_kg_utils-0.1.0.dist-info/METADATA
12 87 02-02-2020 00:00 hy_kg_utils-0.1.0.dist-info/WHEEL
13 450 02-02-2020 00:00 hy_kg_utils-0.1.0.dist-info/RECORD
14 --------- -------
15 9148 6 files
The 02-02-2020 dates are not stale files: Hatchling, the build backend used here, writes a fixed timestamp into every wheel entry so that building the same sources twice produces byte-identical wheels (a reproducible build).
Now create a fresh virtual environment outside the repository, install the wheel, and test both hy -c and python -c:
1 uv venv /tmp/hy_wheel_check
2 uv pip install --python /tmp/hy_wheel_check/bin/python dist/hy_kg_utils-0.1.0-py3-none-any.whl
3 /tmp/hy_wheel_check/bin/hy -c '(require hy_kg_utils [with-graph]) (import hy_kg_utils.core [query->rows]) (print (with-graph [g [#("wheel" "works-in" "hy")]] (query->rows g)))'
4 /tmp/hy_wheel_check/bin/python -c 'from hy_kg_utils import GraphClient, query_to_rows; g = GraphClient("wheel-check"); g.add("wheel", "works-in", "python"); print(query_to_rows(g)); g.close()'
5 rm -rf /tmp/hy_wheel_check dist
Output:
1 [{'subject': 'wheel', 'predicate': 'works-in', 'object': 'hy'}]
2 [{'subject': 'wheel', 'predicate': 'works-in', 'object': 'python'}]
5. Testing Hy Packages with pytest
By default, pytest only looks for test_*.py and *_test.py files. A six-line conftest.py at the project root teaches pytest to collect test_*.hy files as standard Python test modules:
1 import hy # noqa: F401 -- enables importing .hy modules
2 import pytest
3
4
5 def pytest_collect_file(file_path, parent):
6 """Let pytest collect Hy test files named test_*.hy."""
7 if file_path.suffix == ".hy" and file_path.name.startswith("test_"):
8 return pytest.Module.from_parent(parent, path=file_path)
Because Hy functions compile to regular Python function objects and Hy decorators ((defn [decorator] name [args] ...)) attach standard attributes, every pytest feature works in Hy: fixtures with yield, @(pytest.mark.parametrize ...), (pytest.raises ...), monkeypatch, and tmp_path (which Hy’s mangler matches to the parameter tmp-path!).
Here is tests/test_hy_kg_utils.hy:
1 "Pytest suite written in Hy covering fixtures, parametrize, raises, monkeypatch, tmp_path, and macros."
2
3 (import pytest)
4 (import hy_kg_utils [GraphClient])
5 (import hy_kg_utils.core [query->rows])
6 (require hy_kg_utils.macros [with-graph])
7
8
9 (defn [(pytest.fixture)] seeded-client []
10 "Provide a GraphClient preloaded with four sample triples."
11 (setv client (GraphClient :name "fixture-graph"))
12 (.add-many client
13 [#("hy" "compiles-to" "python-ast")
14 #("hy" "is-a" "lisp")
15 #("uv" "manages" "packages")
16 #("mypy" "checks" "types")])
17 (yield client)
18 (.close client))
19
20
21 (defn test-fixture-and-predicates [seeded-client]
22 (assert (= (.count seeded-client) 4))
23 (assert (= (.predicates seeded-client)
24 ["checks" "compiles-to" "is-a" "manages"]))
25 (assert (= (.add seeded-client "hy" "is-a" "lisp") False)))
26
27
28 (defn [(pytest.mark.parametrize
29 "s,p,o,expected_count"
30 [#("hy" None None 2)
31 #(None "is-a" "lisp" 1)
32 #("uv" "manages" None 1)
33 #("unknown" None None 0)])]
34 test-query-to-rows-parametrized [seeded-client s p o expected-count]
35 (setv rows (query->rows seeded-client :s s :p p :o o))
36 (assert (= (len rows) expected-count))
37 (when (> expected-count 0)
38 (assert (= (set (.keys (get rows 0)))
39 #{"subject" "predicate" "object"}))))
40
41
42 (defn test-raises-on-empty-term-and-closed-client []
43 (setv client (GraphClient))
44 (with [(pytest.raises ValueError :match "subject must be a non-empty string")]
45 (.add client " " "is-a" "lisp"))
46 (.close client)
47 (with [(pytest.raises RuntimeError :match "is closed")]
48 (.add client "hy" "is-a" "lisp"))
49 (with [(pytest.raises RuntimeError :match "is closed")]
50 (query->rows client)))
51
52
53 (defn test-monkeypatch-default-graph-name [monkeypatch]
54 (.setenv monkeypatch "HY_KG_DEFAULT_GRAPH" "patched-kg")
55 (setv client (GraphClient))
56 (assert (= client.name "patched-kg")))
57
58
59 (defn test-tmp-path-tsv-roundtrip [seeded-client tmp-path]
60 (setv tsv-file (/ tmp-path "graph.tsv"))
61 (setv written (.save-tsv seeded-client tsv-file))
62 (assert (= written 4))
63 (assert (.exists tsv-file))
64
65 (setv fresh (GraphClient :name "reloaded"))
66 (setv loaded (.load-tsv fresh tsv-file))
67 (assert (= loaded 4))
68 (assert (= (query->rows fresh :s "hy")
69 (query->rows seeded-client :s "hy")))
70
71 (setv bad-file (/ tmp-path "bad.tsv"))
72 (.write-text bad-file "only-two\tcolumns\n" :encoding "utf-8")
73 (with [(pytest.raises ValueError :match "Expected 3 tab-separated columns")]
74 (.load-tsv fresh bad-file)))
75
76
77 (defn test-with-graph-macro-closes-on-exit []
78 (setv rows
79 (with-graph [g [#("hy" "supports" "macros")
80 #("hy" "targets" "python")]]
81 (.add g "pytest" "runs" "hy-tests")
82 (query->rows g :s "hy")))
83 (assert (= (len rows) 2))
84 (assert (= (get (get rows 0) "predicate") "supports"))
85 (assert (= g.closed True))
86
87 (setv expanded (hy.repr (hy.macroexpand-1 '(with-graph [g] (.count g)))))
88 (assert (in "GraphClient" expanded))
89 (assert (in "finally" expanded)))
Notice how (defn [(pytest.fixture)] seeded-client [] ...) defines seeded_client, and any test function declaring [seeded-client] receives that fixture automatically.
6. Interactive REPL Workflow (HYSTARTUP, --spy, and hy2py)
A fast REPL loop is one of the best reasons to write Hy. Three tools make the Hy REPL far more informative than a default session:
HYSTARTUP
When the environment variable HYSTARTUP points to a .hy file, Hy executes that file before showing the first prompt. Here is examples/hystartup.hy:
1 "Example HYSTARTUP file for interactive Hy REPL sessions.
2
3 Launch a REPL with this file:
4 HYSTARTUP=examples/hystartup.hy uv run hy
5 "
6
7 (import importlib [reload])
8 (import pprint [pprint])
9 (import hy_kg_utils [GraphClient])
10 (import hy_kg_utils.core [query->rows])
11 (require hy_kg_utils [with-graph])
12
13 (setv repl-output-fn hy.repr)
14
15
16 (defn expand [form]
17 "Pretty-print one step of macroexpansion for a quoted form."
18 (print (hy.repr (hy.macroexpand-1 form))))
19
20
21 (print "Loaded examples/hystartup.hy: GraphClient, query->rows, with-graph, reload, expand ready.")
Setting (setv repl-output-fn hy.repr) tells the REPL to print results using Hy syntax (#[...], #(...), :keywords) instead of Python’s repr.
hy --spy
Launching the REPL with uv run hy --spy prints the exact Python code generated for every S-expression before executing it:
1 $ HYSTARTUP=examples/hystartup.hy uv run hy --spy
2 Loaded examples/hystartup.hy: GraphClient, query->rows, with-graph, expand ready.
3 => (with-graph [g [#("hy" "is-a" "lisp")]] (.count g))
4 g = hy.I.hy_kg_utils.core.GraphClient()
5 try:
6 _hy_gensym_seed_1 = [('hy', 'is-a', 'lisp')]
7 if _hy_gensym_seed_1:
8 g.add_many(list(_hy_gensym_seed_1))
9 _hy_anon_var_1 = None
10 else:
11 _hy_anon_var_1 = None
12 _hy_anon_var_2 = g.count()
13 finally:
14 g.close()
15 _hy_anon_var_2
16 1
Whenever you wonder how a Hy comprehension, pattern match, or macro compiles to Python, --spy gives you the answer immediately. For an entire file, run uv run hy2py path/to/file.hy.
7. Debugging with breakpoint, pdb, and Name-Mangling Surprises
Because Hy compiles to Python AST nodes with line numbers attached, Python tracebacks and pdb point directly to your .hy source file and line number. You can drop into the debugger anywhere in a .hy file by calling (breakpoint):
1 (defn debug-query [client subject]
2 (breakpoint)
3 (query->rows client :s subject))
Inside pdb, keep two name-mangling rules in mind when inspecting variables:
- Dashes become underscores: If your Hy code binds
(setv raw-line "a\tb\tc"), inpdbyou inspectp raw_line, notraw-line(which Python parses as subtraction:raw - line). - Special characters use
hyx_andX...X: A function namedquery->rowsis stored in the module dictionary ashyx_query_XgreaterHthan_signXrows, and a predicate namedempty?becomeshyx_emptyXquestion_markX. If you need to look up a symbol dynamically inpdb, callhy.mangle("query->rows")or inspect[hy.unmangle(k) for k in dir(mod)].
8. Static Type Checking with #^, deftype, hy2py, and mypy
Hy supports Python’s full type annotation model through the #^ reader macro and deftype (which emits Python 3.12+ type Name = ... statements). Here is the complete src/hy_kg_utils/core.hy:
1 "Core runtime classes and functions for hy_kg_utils."
2
3 (import os)
4 (import pathlib [Path])
5
6 (deftype Triple (get tuple #(str str str)))
7 (deftype Row (get dict #(str str)))
8 (deftype MaybeStr (| str None))
9
10
11 (defn #^ str _clean-term [#^ str value #^ str field-name]
12 "Strip whitespace and reject empty triple terms."
13 (setv cleaned (.strip value))
14 (when (= cleaned "")
15 (raise (ValueError f"{field-name} must be a non-empty string")))
16 cleaned)
17
18
19 (defclass GraphClient []
20 "A small in-memory triple store with TSV import/export."
21
22 (defn #^ None __init__ [self #^ MaybeStr [name None]]
23 (setv default-name (os.environ.get "HY_KG_DEFAULT_GRAPH" "default"))
24 (setv #^ str self.name (if (is name None) default-name name))
25 (setv #^ (get list Triple) self._triples [])
26 (setv #^ bool self.closed False))
27
28 (defn #^ None _check-open [self]
29 (when self.closed
30 (raise (RuntimeError f"GraphClient '{self.name}' is closed"))))
31
32 (defn #^ bool add [self #^ str s #^ str p #^ str o]
33 "Add (s, p, o) if not already present. Return True when added."
34 (._check-open self)
35 (setv triple #((_clean-term s "subject")
36 (_clean-term p "predicate")
37 (_clean-term o "object")))
38 (if (in triple self._triples)
39 False
40 (do
41 (.append self._triples triple)
42 True)))
43
44 (defn #^ int add-many [self #^ (get list Triple) triples]
45 "Add multiple triples and return the number of newly inserted triples."
46 (._check-open self)
47 (setv added 0)
48 (for [[s p o] triples]
49 (when (.add self s p o)
50 (+= added 1)))
51 added)
52
53 (defn #^ int count [self]
54 "Return the total number of stored triples."
55 (len self._triples))
56
57 (defn #^ (get list Triple) match [self
58 #^ MaybeStr [s None]
59 #^ MaybeStr [p None]
60 #^ MaybeStr [o None]]
61 "Return all triples matching the non-None subject, predicate, and object filters."
62 (._check-open self)
63 (lfor [ts tp to] self._triples
64 :if (and (or (is s None) (= ts s))
65 (or (is p None) (= tp p))
66 (or (is o None) (= to o)))
67 #(ts tp to)))
68
69 (defn #^ (get list str) predicates [self]
70 "Return sorted distinct predicate names."
71 (._check-open self)
72 (sorted (sfor [_ tp _] self._triples tp)))
73
74 (defn #^ int save-tsv [self #^ Path path]
75 "Write triples to a tab-separated file and return the row count."
76 (._check-open self)
77 (setv lines (lfor [s p o] self._triples f"{s}\t{p}\t{o}\n"))
78 (.write-text (Path path) (.join "" lines) :encoding "utf-8")
79 (len lines))
80
81 (defn #^ int load-tsv [self #^ Path path]
82 "Load triples from a tab-separated file and return the count of new triples."
83 (._check-open self)
84 (setv text (.read-text (Path path) :encoding "utf-8"))
85 (setv added 0)
86 (for [raw-line (.splitlines text)]
87 (setv line (.strip raw-line))
88 (when (and line (not (.startswith line "#")))
89 (setv parts (.split line "\t"))
90 (when (!= (len parts) 3)
91 (raise (ValueError f"Expected 3 tab-separated columns, got: {raw-line}")))
92 (when (.add self (get parts 0) (get parts 1) (get parts 2))
93 (+= added 1))))
94 added)
95
96 (defn #^ None close [self]
97 "Mark the client closed."
98 (setv self.closed True)))
99
100
101 (defn #^ (get list Row) query->rows [#^ GraphClient client
102 #^ MaybeStr [s None]
103 #^ MaybeStr [p None]
104 #^ MaybeStr [o None]]
105 "Query client and return sorted dictionary rows with subject/predicate/object keys."
106 (setv matches (sorted (.match client :s s :p p :o o)))
107 (lfor [ts tp to] matches
108 {"subject" ts
109 "predicate" tp
110 "object" to}))
111
112
113 (setv query-to-rows query->rows)
114
115
116 (export
117 :objects [Triple Row MaybeStr GraphClient query->rows query-to-rows])
Two syntax rules in core.hy are worth memorizing:
- Generic subscripting uses
(get ...): In Python, generic types use square brackets (list[Triple],tuple[str, str, str],dict[str, str]). In Hy,(list Triple)is a function calllist(Triple), whichmypyrejects as an invalid type annotation. Always write(get list Triple)for single-argument generics and(get tuple #(str str str))for multi-argument generics. - Annotating parameters with default values: Place
#^ Typeoutside the[param default]bracket: write#^ MaybeStr [s None], not[#^ MaybeStr s None].
When we run uv run hy2py src/hy_kg_utils/core.hy, Hy emits standard annotated Python:
1 type Triple = tuple[str, str, str]
2 type Row = dict[str, str]
3 type MaybeStr = str | None
4
5 def _clean_term(value: str, field_name: str) -> str:
6 """Strip whitespace and reject empty triple terms."""
7 cleaned = value.strip()
8 if cleaned == '':
9 raise ValueError(f'{field_name} must be a non-empty string')
10 _hy_anon_1 = None
11 else:
12 _hy_anon_1 = None
13 return cleaned
Our scripts/typecheck.sh script translates the .hy modules into a temporary build directory and runs mypy with strict = true:
1 #!/usr/bin/env bash
2 set -euo pipefail
3
4 cd "$(dirname "$0")/.."
5
6 BUILD_DIR="build/typecheck"
7 PKG_OUT="${BUILD_DIR}/hy_kg_utils"
8
9 rm -rf "${BUILD_DIR}"
10 mkdir -p "${PKG_OUT}"
11
12 cp src/hy_kg_utils/__init__.py "${PKG_OUT}/__init__.py"
13 uv run hy2py src/hy_kg_utils/macros.hy > "${PKG_OUT}/macros.py"
14 uv run hy2py src/hy_kg_utils/core.hy > "${PKG_OUT}/core.py"
15
16 echo "=== Translated Python modules in ${PKG_OUT} ==="
17 ls -1 "${PKG_OUT}"
18
19 echo "=== Running mypy on translated core.py and __init__.py ==="
20 MYPYPATH="${BUILD_DIR}" uv run mypy --config-file pyproject.toml "${PKG_OUT}/core.py" "${PKG_OUT}/__init__.py"
21
22 rm -rf build .mypy_cache
Notice that scripts/typecheck.sh translates macros.hy so imports resolve, and runs mypy --strict on core.py and __init__.py. Because defmacro expands into an untyped compiler helper function that returns hy.models.Expression trees, keeping compile-time macros in macros.hy and typed runtime code in core.hy gives you strict type checking on all runtime APIs without fighting macro expansion internals.
9. Editor and LSP Options
As of this edition (November 2026), three community tools provide syntax highlighting, structural editing, and language-server completions for Hy:
- Hyuga (
hyuga): A Language Server Protocol (LSP) server for Hy (uv tool install hyuga). It provides autocomplete, hover docstrings, and jump-to-definition for both Python imports and Hy forms across VS Code, Emacs (eglotorlsp-mode), and Neovim. - tree-sitter-hy: A Tree-sitter grammar for Hy that powers accurate highlighting and structural selection in Neovim (
nvim-treesitter), Helix, and Zed. - Emacs
hy-mode+paredit/smartparens: Remains a favorite for Lisp programmers who want slurp/barf S-expression editing andinferior-lispREPL evaluation (C-c C-z).
10. Formatting and Linting
Never run Python formatters such as ruff format or black directly on .hy files; they expect Python syntax and will fail with parse errors. Instead, as of this edition (November 2026):
- Use Beautifhy (
beautifhy) to format.hyfiles according to Lisp indentation conventions (2-space indent insidedefn,defclass,with,let, and aligned bindings). - If you want static lint checks for unused imports or unreachable branches, run
hy2pyintobuild/typecheck(just asscripts/typecheck.shdoes) and runruff checkon the generated.pyfiles, ignoring Hy’s synthetic_hy_anon_*variables.
11. Continuous Integration and Release Checklist
The example directory includes a ready-to-use GitHub Actions workflow at source_code_for_examples/hy_kg_utils/.github/workflows/ci.yml that tests the package across Python 3.12, 3.13, and 3.14, runs the hy2py + mypy check, and verifies that uv build succeeds:
1 name: CI
2
3 on:
4 push:
5 branches: [main]
6 pull_request:
7
8 jobs:
9 test:
10 runs-on: ubuntu-latest
11 strategy:
12 fail-fast: false
13 matrix:
14 python-version: ["3.12", "3.13", "3.14"]
15
16 steps:
17 - name: Check out repository
18 uses: actions/checkout@v4
19
20 - name: Install uv
21 uses: astral-sh/setup-uv@v6
22
23 - name: Set up Python ${{ matrix.python-version }}
24 run: uv python install ${{ matrix.python-version }}
25
26 - name: Sync dependencies
27 run: uv sync --python ${{ matrix.python-version }}
28
29 - name: Run pytest suite (Hy and Python tests)
30 run: uv run pytest -v
31
32 - name: Run hy2py + mypy typecheck
33 run: bash scripts/typecheck.sh
34
35 - name: Build wheel and sdist
36 run: uv build
When you are ready to publish a release to PyPI:
- Bump
versioninpyproject.tomland__version__insrc/<pkg>/__init__.py. - Run
uv sync,uv run pytest, andbash scripts/typecheck.sh. - Build artifacts with
uv buildand inspect the wheel withunzip -l dist/*.whlto confirm all.hyfiles are present. - Publish with
uv publish(using PyPI Trusted Publishing in GitHub Actions or an API token).
12. Migration Tools: hy2py and py2hy
Two translation utilities help when migrating code between Python and Hy (as of this edition, November 2026):
hy2pyships with Hy itself (uv run hy2py file.hy). Because it runs Hy’s own reader, macroexpander, and AST compiler and then unparses the resulting Python AST,hy2pyis always 100% faithful to the installed Hy version. If you ever need to hand a Hy prototype to a team that only maintains Python,hy2pygives you working Python code in one step.py2hy(maintained in thehylang/py2hyrepository) translates Python source code into Hy S-expressions by walking Python’sastmodule. It is a great starting point when porting an existing Python module to Hy: runpy2hyto get the mechanical translation, and then refactor verbose Python idioms into idiomaticlfor,match, or macros.
Wrap Up
In this chapter we took a Hy codebase from a standalone script to an installable, type-checked, and tested package (hy-kg-utils). By starting __init__.py with import hy, including *.hy in the wheel build configuration, separating compile-time macros from typed runtime modules, and wiring hy2py into mypy and pytest, your Hy libraries become first-class citizens of both the Hy and Python ecosystems.
Exercises
- Small exercise (Predicate filter macro): Add a macro
(with-predicates [var client] #* body)tosrc/hy_kg_utils/macros.hythat bindsvarto(.predicates client)and executesbodyonly when the graph has at least one predicate. Export it and write a test for it intests/test_hy_kg_utils.hy. - Open-ended exercise (CLI entry point and JSONL export): Add a
src/hy_kg_utils/cli.hymodule with amainfunction that reads a TSV file of triples, runs a subject/predicate/object filter fromargparse, and prints matching rows as JSON Lines. Expose it under[project.scripts]inpyproject.toml(via a wrapper function in__init__.py), rebuild the wheel, and verify the installed CLI command in a fresh virtual environment.
Further Reading
- Claudio Jolowicz, Hypermodern Python Tooling (O’Reilly, 2024)