Hy 1.0 – Lisp dialect for Python
github.com
github.com
Also, looking at the code on Github suggests this compiler is written in Python (see https://github.com/hylang/hy/blob/master/hy/compiler.py).
I kind of wish this was made more clear on the main website. Perhaps, instead of introducing Hy as "a Lisp dialect that's embedded in Python", introduce it as "a Lisp dialect that compiles to Python's AST". The words "embedded in Python" don't make it very clear just how it's embedded into Python. The various ways you can embed a Lisp look very different and have very different tradeoffs.
For example, off the top of my head, I could "embed" a Lisp by writing an interpreter (in C if I care about performance) and letting it be called from Python, perhaps passing in a Python list instead of a string to make it more "native". Or I could "embed" a Lisp by compiling to Python bytecode. Or I could "embed" a Lisp by translating it directly to Python source code. Etc.
Regardless, interesting project!
> ...because this is a frontend like LLVM or GCC that compiles instead of bytecode, uh, to Python AST, um, so this Lisp compiles entirely to Python
Yes, that's right. Hy is not self-hosted.
> The various ways you can embed a Lisp look very different and have very different tradeoffs.
Hy itself provides options. Typically the process is that the Hy source code becomes Python AST objects, which Python then complies and executes, but you can also translate the Python AST objects into Python source text. Or you can use Python from Hy or vice versa: https://hylang.org/hy/doc/v1.0.0/interop
> Hy is a Lisp dialect that's embedded in Python. Since Hy transforms its Lisp code into Python abstract syntax tree (AST) objects, you have the whole beautiful world of Python at your fingertips, in Lisp form.
A few examples from recent releases:
- "match" is just native Python "match" -- it doesn't even polyfill for pre-3.10 Python versions (in the TypeScript world this would be unthinkable)
- "foo?" used to mangle to "is_foo" as a special case, but this has been removed
- "hy.eval" has been overhauled to be more like Python's "eval"
- nice-to-have but non-essential utilities ("unless") get often pushed out into the Hyrule package
For me this direction was counter-intuitive at first, but it has some very nice outcomes; for one, it simplifies the learning curve when coming over to Hy from Python, and it makes it easier to consistently interact with Python packages (arguably the main reason to use Python in the first place!)
Or maybe it's just a matter of simplyfing maintenance of the language; IIRC, "let" took like 4 attempts to get right :)
In any case, congratulations on this great milestone!
It also demonstrates that elegance in a Lisp-on-Python is reached in a very different way than elegance in a stand-alone language, since it becomes an art of making the best out of what is already there.
Hehe, clever.
By the way, Hy works really well inside https://holzschu.github.io/a-Shell_iOS on the iPad, although the syntax highlighting in vim/neovim needs to catch up to the 0.29+ releases and async.
Although I've tried using Fennel and Guile instead over the years, having access to Python libraries and ecosystem is preferable to me, and with async I can do some very nice, efficient API wrangling (doing HTTPS with fine-grained control over socket re-use and headers remains a pain in various Schemes, so I very much prefer using aiohttp)
I saw the original lightning talk that introduced Hy to the world at Pycon those ages ago. Soon after I met Paul and started contributing to the early versions of Hy. I was responsible for the CL-style kwargs (you’re welcome), some minor innards, and a library or two.
Whimsy is useful, especially to keep enthusiasm up. It’s nice when hackers can be hackers and not every thing is business.
While I haven’t been involved in years it brings a smile to me face to see the project continues apace. What a great milestone!
A Clojure-compatible(-ish) Lisp dialect targeting Python 3.8+ https://github.com/basilisp-lang/basilisp
I'd be seriously interested in hearing from people that have actually used any of these two and what their experience was.
By contrast Hy generates Python code that is very close to what you might write by hand, apart from some indirection when it comes to scoping with `let` and some variations around returning values.
Maybe Coconut has improved though, it's been a long time.
1. Does it support REPL-driven development? (condition system, breakloop, etc.)
2. Is there a standalone distribution? Distributing python in itself is a hassle, ideal situation would be to simply distribute a single Hy binary that contains all dependencies within it (either statically linked or as a zip file extracted in tmp directory).
uvx hy@1.0.0
gets you into the Hy REPL echo '(print "hi hn")' > hi.hy
uvx hy@1.0.0 hi.hy
prints "hi hn"https://docs.astral.sh/uv/guides/tools/#running-tools
(context: uv can install and manage python versions)
2. No, sorry.
Seems like that would only be doable by altering CPython to at least have a hook in the initial exception processing (or maybe there is some magic double-underscore thing for that already?).
>A convenient way to use this class to interactively debug code is to insert the following in the code you want to debug:
(.run (hy.REPL :locals {#\* (globals) #\* (locals)}))
>Or in Python: import hy; hy.REPL(locals = {\*globals(), \*locals()}).run()
>Note that as with `code.interact()`, changes to local variables inside the REPL are not propagated back to the original scope.I wrote a book oh Hy, so now tomorrow I will update all the examples to version 1.0
Not counting work on my book, I don’t use Hy more than perhaps five hours a month, but it is a fun language, with good Emacs support. Thanks!
More concrete: Are there Python language features I can't use in Hy? Or performance penalties in using Hy?
At the semantic level, no. I work to cover 100% of Python AST node types with Hy's core macros. It does take me a little bit to implement a new core macro after the CPython guys implement a new feature, but you can always use the `py` or `pys` macros to embed the Python you need, should it come to that.
> Or performance penalties in using Hy?
Compiling Hy (that is, translating it to Python AST) can be slow for large programs (I've seen it top out at about 3 seconds), but at runtime you shouldn't see a difference. Hy always produces bytecode, which can be used to skip the compilation step if the code is unchanged.
I'm now figuring out how to pack images to OpenAI REST calls (using my own REST wrapper), and everything is peachy. Here's my test snippet (mostly to b64encode the file):
(import aiohttp [ClientSession]
base64 [b64encode]
asyncio [run])
(defn :async pack-image [filename]
(with [h (open filename "rb")]
{
"type" "image_url"
"image_url" { "url" f"data:image/jpeg;base64,{(.decode (b64encode (.read h)) "utf-8")}" }
}))
(defn :async main[]
(print (await (pack-image "request.hy"))))
(run (main))
This shows you async, context managers, selective imports, f-strings... etc. All that you need, really.Why not just use something closer to the metal: Common Lisp, Scheme, Clojure, Racket? Especially, use a compiled language, instead of an interpreter.
I just read through the author list on the Hy repo and had a glimpse into their blog posts. Cool stuff, great work.
I looked at the Hy vs Python comparison, Hy is just as (if not more) verbose as Python and harder to read and reason about.
Honest inquiry here, what is the appeal or benefit of the Lisp syntax? is it just that some people have a subjective preference for it?
In blub lang based on c:
Fn(Val Val Val) to f(1,2,3) or
Val fn val 3 + 3
In blub lang based on lisp
(Fn val val...)
In real world Lisp, alignment conventions are used that make even a fairly nested function readable at a glance. You'd also generally work using something like paredit, so you're kind of shuffling the S-expressions around like legos. It's not a language that you'd want to write in something like Notepad.
The most important thing about the syntax, though, is that since it's basically the AST, a Lisp macro can effectively manipulate the AST directly and on the fly. This is incredibly powerful, and would be hard to achieve in an Algolian language like Python.
Thanks for suggesting paredit.
The placement of parentheses is not arbitrary. The parentheses enclose expressions, and the nesting of expressions builds a tree. This tree, in effect, is your program's AST. Your C program compiles to something very similar; Lisp just makes it explicit.
"Add x y z" is exactly what it sounds like, if I said those words to you. The add function is usually +, so (+ x y z) is an expression that adds x, y and z, and the whole expression evaluates to the result. You can nest expressions however you like, so, for example, (+ x (* a b)) adds x to the result of the expression (* a b), which evaluates to the result of multiplying a by b.
Values and expressions are effectively interchangeable. Any one of +, x, or y, could be replaced by an arbitrarily complex expression (yes, the function too - you could replace it with a call to a higher order function, which would return a function that is then called over x and y).
The neat thing is, that's basically[0] all the syntax Lisp has. There are no reserved keywords. Everything works as per above, and can be redefined at will. You can change the language's if and else to work any way you want. You can redefine Lisp's reader to change the syntax of the language to absolutely anything you can imagine, and doing so is quite easy, since you're effectively already working at the AST level.
And you can do all of this in a running REPL without even needing to restart it.
If you're interested, check out Common Lisp: A Gentle Introduction to Symbolic Computation by David S. Touretzky.
[0] Macros are the other piece of the puzzle, but to understand them you would need to read up on Lisp more. Once you understand Lisp macros, the advantages of Lisp's syntax become obvious.
See also: https://paulgraham.com/avg.html
Take a look at Racket languages for some examples.
Lisp syntax with the parens and so on means editing is inherently structural, which makes it relatively easy to reason about and restructure the code. In Python spaces have double meanings, both as separator between tokens and as a block separator, similar to e.g. {} or () in other languages. That makes structural editing relatively hard.
it is a bit ackward for humans but machines can process it better because it has less structure. for example what I thought is that Lisp could potentially be a great choice to interop with Large Language Models with, because its potentially shorter code. Good clojure code can be 5-10x shorter than python code. With LLMs size of code matters a lot.
(func (param i64) (result i64)
local.get 0
i64.eqz
if (result i64)
i64.const 1
else
local.get 0
local.get 0
i64.const 1
i64.sub
call 0
i64.mul
end)
https://en.wikipedia.org/wiki/WebAssembly#Code_representatio...- It makes editing and refactoring code faster. With a single keystroke you can do things like popping bits of code in or out of scope, deleting logical blocks of code etc. It's fast.
- It's hard to explain without trying it, but it is faster and less error prone to e.g. grab a section of code inside a function and break it out into a separate function. If your lisp is functional this is even smoother (hy is not as functional as it could be last time I checked).
- You never have to think about syntax. Python for example has different syntax for different operations and introduces new syntax relatively frequently. By contrast in a lisp the syntax for setting a variable looks the same as the syntax for looping and for everything else. It's all just function calls.
- If you have an nREPL set up (it's like the python repl but it's an API your editor can talk to) it makes it easier to run segments of code that are embedded inside other bits of code. E.g. you might have some complicated piece of maths or string manipulation in a function. You can run and try it out in isolation without executing the entire function.
- Metaprogramming. This is a bit overhyped for most programmers, but having the code as a data structure means you can add new language features from your own code, build DSLs, and have code that modifies other code more easily than in other languages. I try not to use metaprogramming and macros much, but I use a lot of things that smarter people than me have made with them.
These features are a bit hard to appreciate without trying them. Highly recommended!
Not really.
Setting a variable in Lisp is not a function call. IF is also not a function call. Defining a function is also not a function call. Loop operations like DO, DOLIST, DOTIMES, ... are also not function calls. Lots of things are not function calls. Macro forms are also not function calls.
(let ((a 10) (b 20) c)
(declare (type (integer 0 *) a b c))
(setf c (* a b))
c)
Above is a LET expression, a variant of a lambda application.It does not look like a function call. It looks like an operator list form, with LET as the operator. The next element is not a function call or similar, but a binding list with three variable definitions, two of them having an init value. Next to the binding list is a declaration form, with a type declaration for the local variables. Then a sequence of forms, a body, which is evaluated top down and the last value ist returned. There is a setf form, for setting a variable. The variable in the setf form is not evaluated, it will be set to the value of the second argument.
Neither LET, DECLARE, TYPE, INTEGER, or SETF are functions. They have different syntax and/or semantics from function calls.
Thus we have:
* special control flow
* a LET syntax which is not looking like a function call
* a lexical scope created by LET
* a type declaration with special syntax
* special evaluation rules, unlike evaluation of a function form
A Lisp user will need to learn that IF, WHEN, AND, ... and a lot of other operators are not functions....
For examples, McCarthy's original purpose was to demonstrate the effectiveness of a symbolic differentiation process he had dreamt up, so he devised the syntax and meta-circular evaluator of lisp to make it maximally obvious from the program text that the differentiation system was mathematically correct, while keeping it maximally obvious from the program model definition that it was computationally concrete. In response to new trends in the programming field, Lispers write mind-bending books like "Let over Lambda", "The Art of the Metaobject Protocol", or "Software Design for Flexibility" to show that, when your syntax and model is right, you can radically change how you solve problems not by rewriting your spec or switching languages but by just adding more lisp to the lisp you already have, which has the same simplicity as radically increasing the sculptures a child can make by just adding more lego to the lego they already have.
Lisps, on the other hand, tend to add features as just more convenient versions of things they can already do: Macrology for self-adapting code? Just lisp functions on lisp data structures corresponding to lisp functions. Actors for a concurrent execution model? Lisp functions as lisp data parameterized by higher-order lisp functions. Composable continuations for error handling? A lisp function exploring a lisp data structure of lisp data structures of lisp functions. It's turtles all the way down. Paul Graham points out that you can understand the social hype the presence or absence of a feature like operator overloading as a consequence of friction-ful syntaxes, while lispers care much less because replacing a function you don't prefer with one you do for your use case is straightforward in a friction-free syntax. When he decided to build a reddit clone for tech entrepreneurs he didn't need an outside data system just to get started, he only had to spin up a pool of threads for sessions to directly modify s-expression literals in memory, which he could save or modify by printing straight to disk and load by just reading the lisp syntax back into memory like all lisp code is, with no execution intermediary like languages such as the Pythons tend to have complicating things enough to make comparatively big services like a whole database for a private gossip forum worth the effort. The syntax doesn't make lisp first-order beautiful, it makes lisp the hacker's local maximum, which is second-order beautiful, and honestly isn't much harder to get into the habit of reading once you know it's worth it.
If trolling, it is not very subtle. :-)
The real power of lisp IMHO lies in:
- Repl driven, dynamic development. This is hard to explain. Its like chocolate. You have to try it. You either love it or hate it.
- Macros. This is again enabled by the 'lisp syntax. Actually lack of it...'.
Here is an example I recently ran into when checking out Hyhttps://github.com/hylang/hy/discussions/2608#discussioncomm...
This shows how much you can abstract, hide the noise without any runtime penalties..
https://www.codesections.com/blog/raku-lisp-impression/
[thanks to Larry Wall’s penchant for collecting stuff]
letrec, lambda, or & and are not functions in Scheme.
(Does `let` work? I remember that being a barrier for a while.)
Years ago, under the influence of Lisp romanticism late into my university years, I worked on a domain-specific language for designing and analyzing control systems as my senior design project, using Hy! Just checked, it's been five and a half years to be specific. Really, time flies.
Here it is for anyone curious: https://github.com/celaleddin/gently
Since then, I've been following Hy from a distance and it's amazing to see it's still active. Thank you everyone involved!
Also great timing after the recent Python Preprocessor post: https://pydong.org/posts/PythonsPreprocessor/
Could Hy hypythetically be implemented as a preprocessor like https://github.com/tomasr8/pyjsx?
I’m curious about the macros: how are these implemented? They seem like pretty straightforward unhygienic Lisp macros, which is a little bit of a disappointment, but better some macros than none at all! Anything about the macro system that distinguishes it from the Common Lisp system? E.g. anything borrowed from Scheme or Racket? Docs are sparse here.
(Also, use something to insure your own internal packages have a higher priority, alright? That’s a lesson I didn’t need to learn twice.)
(I'm also probably a little spoiled with documentation coming from Racket which has like 4 big chapters dedicated to different aspects of macros scattered around the docs, plus some associated papers. Forgive me—I'm not trying to dunk on Hy; I just like reading docs.)
Quite the opposite, they are more powerful than the alternatives.
Macros are power tools, dumbing them down for safety is missing the point.
I want my macros to be easy to write correctly. That can only happen when the system has proper hygiene.
If you put your own symbols into generated code you better have a damn good idea what you're doing.
It's a power tool.
If you are wanting to introduce variable capture you better be really explicit about when you want it.
If there’s no hygiene, I have to know everything about how the macro is implemented in order to trust it and use it confidently. Might be fine for small shorthand, but that won’t scale. You need non-leaky abstractions to build on them.
Racket’s `syntax-parse` and “syntax parameters” show that you can have it both ways: procedural macros that are hygienic by default, but with an explicit escape hatch when you do want to introduce new bindings into the macro call site. It also gives you much much better errors.
CL macros are about as dangerous as malloc/free, but without years of experience and tools like Valgrind to debug. They’re hard to trust and get right.
Racket macros are like GC/affine typing: everything is correct by construction.
Of course we want them to be as safe as possible, but that's a different discussion. All attempts I've seen so far have dropped functionality to get there.
Well, then I recommend you take a look at Racket's macro system: Racket gives you hygienic macros without any loss of power. (It's actually more powerful and expressive than CL macros.)
Racket's model is much more sophisticated and powerful. The input to a macro in Racket is a syntax object [1], which combines the CL-like quoted expression with additional source and lexical binding information. This means that in Racket, unlike CL, a variable is not just it's name—it's also all this other information. Racket uses scope sets to track binding information in a sane and hygienic manner across different macros and functions.
So, if you want to introduce an identifier that the macro caller can interact with (note: I said an identifier—you can introduce any symbols you want but they'll be different identifiers because their scope sets will be different) you need to explicitly state that you would like to create an identifier with a particular scope set. [4]
But that's the old, dumpy, clunky way of doing things. Thanks to recent research, we have much better ways of introducing identifiers in a sane, hygienic way. Gregg Hendershott's excellent "Fear of Macros" walks through making the `aif` macro using syntax parameters [3] which let you cleanly introduce new bindings. (See the paper "Keeping it Clean with Syntax Parameters" he's linked to in his post.)
So, in short, no, we're not back to regular CL macros because Racket prevents us from accidental variable capture but gives us an easy way to do 99.999% of the use cases for breaking hygiene (syntax parameters) and then one more way (`datum->syntax`) just in case we really need to do something out of the ordinary. In either way, Racket lets you express your intent with macros better and more precisely than CL.
[1]: Racket syntax objects: https://docs.racket-lang.org/guide/stx-obj.html
[2]: Syntax model, scope sets: https://docs.racket-lang.org/reference/syntax-model.html
[3]: "Fear of Macros", writing the `aif` macro: https://www.greghendershott.com/fear-of-macros/Syntax_parame...
[4]: Reddit thread on making an unhygienic macro: https://www.reddit.com/r/Racket/comments/tpgaa4/is_there_a_w...
Could you compare the language with Clojure?
I get the impression that Clojure tries to convince the programmer to avoid side-effects a lot more strenuously than Hy does, but it's still not a purely functional language, so I don't know how consequential that is in practice.
Clojure does not work with Java ASTs, it translates into JVM bytecode directly.
Wondering how custom immutable data structures fit in with the Python ecosystem.
Particularly, I know that NumPy arrays and Pandas Series/DataFrames are the popular data structures used in research computing in Python (for Statistics, Data Science, Machine Learning etc.). These data structures afaik are mutable, however (for performance reasons), so at least the aspect of immutability from Clojure cannot be easily integrated with the Python ecosystem.
I've tried to facilitate strong Python interoperability despite the variety of otherwise incompatible features of each language. It's trivial to work with immutable data structures using Clojure idioms and then convert them to Python data structures (as needed) at the boundaries, but the immutable data structures used by Basilisp are also generally compatible with Python's core (read-only) interfaces so that conversion may also not be necessary if you aren't expecting the called function to perform any mutations.
Dynamically shadowing global variables is not built-in, but easy to write a macro for if you want it. See e.g. https://stackoverflow.com/a/71618732
It would be awesome if there were an example of something that can't be done in Python because it takes advantage of lisp's "functions are first class".
Edit: actually, confusingly, the GitHub repository for Mojo doesn't have an interpreter. The language is still proprietary.