Questions tagged [hy]
Hy is a Lisp dialect that's embedded in Python.
99
questions
0
votes
1
answer
18
views
with-gensyms Error With Hy Documentation Example Code
I am fairly new to Hylang and I am trying to get the last two code snippets here to work. No matter what I do I get the error that with_gensyms is not defined. I am running hy version 0.27.0, which ...
0
votes
1
answer
42
views
No diffs from pytest AssertionErrors when straying from common test file name scheme
I have the following conftest.py for a pytest plugin for hy, adapted from the official hy conftest, but AssertionErros are not diffed for files beginning with test-, only test_, even when using -vv on ...
0
votes
1
answer
85
views
Imported modules not working with macros (anymore)
With the following pytest file:
(import pytest [mark])
(import pathlib [Path])
(require oreo [with-cwd])
(defn [mark.with-cwd] test-with-cwd [cookies]
(let [ cwd (.cwd Path) ]
(with-...
1
vote
1
answer
103
views
Valid Hy Code throws an unexpected end of input error?
this is an exert of the code foor a game that I am writing.
(for [sprite self.sprites]
(if (!= (type sprite.content) NoneType)
(sprite.content.render)))
it complains about a parse ...
0
votes
1
answer
52
views
Locally rebinding `+`
How to translate this Clojure code to Hy, so it prints 2?
It doesn't need to be like Clojure, i just want to hide + and replace it with - in local environment.
(defmacro q [expr]
`(let ~'[+ (fn [x y]...
0
votes
0
answers
118
views
Is there a way to get auto-complete(IntelliSense) for hy?
I have ubuntu 22.04 and hy 0.25
I tried hy-mode, i failed.
I installed doom emacs, but i got this
I also tried to install hy 0.20.0 and i failed again i got this.
If anyone has auto-complete for hy, ...
1
vote
1
answer
159
views
How to convert Numpy special syntax to Hy
I have this Python code:
import numpy as np
import matplotlib.pyplot as plt
X = np.random.randn(500, 2)
plt.scatter(X[:,0], X[:,1])
But I don't know how to convert X[:,0] and X[:,1], which I think ...
0
votes
1
answer
132
views
How to type-hint in Hy
Is it possible to type-hint variables and return values of functions in Hy language?
# in python we can do this
def some_func() -> str:
return "Hello World"
0
votes
1
answer
92
views
How to set two variables at once in Hy
I just started learning Hy (my first attempt at a Lisp dialect). I have a function that returns a tuple of 2 values, and I don't know how to receive it:
(defn function [] #("Hello" "...
0
votes
1
answer
44
views
Requiring `hy' macro with `raise' function triggers `raise' on `require'
When trying to require the following macro in another file, the raise seems to be triggering immediately:
(defmacro assert [a [b True] [message None]]
`(unless (= ~a ~b) (raise (AssertionError (or ...
0
votes
1
answer
71
views
Require macros from the same file in another macro
In the following code, given that hy seem to give a NameError when not explicitly requiring a macro's dependent macros, how do I require a macro in the same file in another macro?
(defmacro with-cwd [#...
2
votes
1
answer
60
views
Non-existent hy macros runs assertions, but fails appropriately with everything else
In the following code:
(eval-and-compile (import os hy))
(eval-and-compile (import pathlib [Path]))
; (defmacro with-cwd [dir #* body]
; (setv cwd (hy.gensym))
; `(let [ ~cwd (.cwd ...
0
votes
1
answer
141
views
__init__.py for hy modules with relative imports
How do I require all functions in a hy module in an __init__.py? I tried to use a similar model as in the hyrule __init__.py, but am getting the following error:
Traceback (most recent call last):
...
0
votes
1
answer
52
views
Mimic `let' statement in a macro
In the following directory structure:
.
├── a
│ ├── 1
│ ├── 2
│ ├── 3
│ └── 4
├── b
│ ├── 5
│ ├── 6
│ ├── 7
│ └── 8
├── c
├── d
└── test.hy
The following code prints the wrong path:
(eval-and-...
0
votes
1
answer
37
views
Difference between using a for loop to run a body in a macro versus mapping `exec' over the body
What's the difference between using (map exec ~body) versus (for [node ~body] node) in the following code?
(defmacro with-cwd [dir #* body]
`(let [ cwd (.cwd Path) ]
(try (....
0
votes
0
answers
18
views
How does the official `hylang/hy' repo run its pytests on its native / `.hy' files? [duplicate]
Is a custom plugin used, such as pytest-hylang or hytest?
0
votes
0
answers
49
views
LexException: f-string: trailing junk in field
In doing the following, I'm getting the error LexException: f-string: trailing junk in field:
(nixos-install #* ctx.args
:I (with [f (open (+ resources "/flake.lock"))]
...
1
vote
2
answers
236
views
Show whether a Python module is loaded from bytecode
I'm trying to debug Hy's use of bytecode. In particular, each time a module is imported, I want to see the path it was actually imported from, whether source or bytecode. Under the hood, Hy manages ...
2
votes
1
answer
59
views
importing module from current folder in hy
Has import changed in Hy version 1.0a4+199.g22021c56?
I'm trying to import a file from the same folder (or cwd), but I get ModuleNotFoundError: No module named 'thenameofthefile'
Even if I append ...
1
vote
2
answers
107
views
hy build-in with-decorator throws NameError: name 'with_decorator' is not defined
I'm trying to run the with-deocorator example from hy manual (https://docs.hylang.org/en/stable/language/api.html?highlight=with-decorator#with-decorator):
(defn inc-decorator [func]
(fn [value-1 ...
1
vote
1
answer
41
views
Cut from negative integer to last item in list in Hy
If (list (range 10)) is [0 ... 9], and (cut (list (range 10)) -5 -1) is [5, 6, 7, 8], then how do I include the last item in the list as well, i.e. [5, 6, 7, 8, 9]? I've tried (cut (list (range 10)) -...
2
votes
2
answers
112
views
Dynamic bindings with let in Hy?
Comming from Common Lisp, I'm trying to use let to shadow the value of a global variable dynamically.
(setv glob 18)
(defn callee []
(print glob))
(defn nonl [x]
(callee)
(let [glob x]
(...
0
votes
1
answer
99
views
Does Hy have inline if?
What is the Hy equivalent of Python's a if condition else b?
I'm trying to convert something like this
return (quicksort(under) if under else []) + same + (quicksort(over) if over else [])
to Hy. It ...
1
vote
1
answer
68
views
Why is this quicksort overflowing?
I have the following Hy code:
(defn quicksort [lst]
(if (< (len lst) 2)
(return lst)
(do
(setv pivot (// (len lst) 2))
(setv (, under same over) (, [] [] []))
...
0
votes
1
answer
56
views
Convert python literal_eval string to hy
I would like to convert the following to Hy, but I can't seem to figure out how to do it; is there perhaps a way to convert a string of python code to the hy syntax? I don't know if py would work ...
0
votes
1
answer
33
views
Render mangled hy attribute names as regular strings
If I have an attribute self.internal/freezer in a class, and I raise an error via (raise (AttributeError f"Sorry! '{attr}' doesn't exist as an attribute!")), how can I get the attribute name ...
0
votes
1
answer
67
views
"Ran into a RPAREN where it wasn't expected" when using "->>"
I have the following code:
(require [hyrule [-> ->>]])
(defn static/freezer [value freezer]
(cond [(not value) (setv freezer [])]
[(...
0
votes
1
answer
52
views
Access attribute and method names with slashes or asterisks defined in Hy from Python
If I were to do the following:
(setv a/b 12)
How would I access the variable in Python, such as from a regular python module, or simply using (py)?
(py "print(a/b)")
0
votes
1
answer
113
views
Expanding macro results in KeyError
With the following (simplified) code:
(setv agnostic-manager-installers {})
(defmacro alias-assign [am &rest aliases]
(for [alias aliases] (assoc
agnostic-manager-installers
(...
0
votes
2
answers
106
views
Using `click` in a shell script that has a Hy program in a here document
How can I convert the following working example of using click with shell + python repl (I think) to hy?
python3 - "$@" <<'EOF'
import click
@click.command()
@click.option('--count', ...
1
vote
2
answers
194
views
Use get in threading macro
The following three examples fail with the following errors:
(setv dct {1 2 3 4})
(setv dcts "dct")
;; (print (get (. (globals) [dcts]) 1))
(print (-> (globals) (. [dcts]) (get 1)))
;; (...
1
vote
1
answer
55
views
Multiple iterators in "for", "lfor", etc. with something like "dct.items()"
How could I convert the following to hy?
dct = { 1:2, 3:4 }
print([i*j for i, j in dct.items()])
# => [2, 12]
1
vote
3
answers
106
views
Hylang "in" operator
Is there an in operator in Hylang? In python, for example, this would allow for the following test:
lst = [1, 2, 3, 4]
print(0 in lst)
# => False
0
votes
5
answers
180
views
Cosine Similarity in linear time using Lisp
The cosine similarity of two lists can be calculated in linear time using a for-loop. I'm curious as to how one would achieve this using a Lisp-like language. Below is an example of my code in Python ...
0
votes
0
answers
79
views
Parse arguments in Hy macro
I need help with parsing arguments in a Hy Macro that generates code for a class.
What I am trying to accomplish: A macro that will generate a class with predefined properties. The property names are ...
1
vote
3
answers
244
views
How to write a macro like dot(.) operator in hylang?
We have some async properties (using @property) and some usual ones. We have to use hy to check if one is async or not using asyncio.iscoroutine function. The problem is we have to use getattr and not ...
0
votes
1
answer
94
views
Hy equivalent to * operator in Python's function arguments that forces keyword arguments
Recently I have been trying to write a simple bot in Hy with Discord.py. In Discord.py we can write a command like this to turn the last argument into a full string that includes spaces:
@commands....
1
vote
1
answer
62
views
macro inside of macro creates a list of None
I have defined two macros:
(defmacro property [name type]
`(setv ^(of Optional ~type) ~name None))
(defmacro data-type [vname &rest propertys]
`(with-decorator dataclass
(defclass ~vname [...
1
vote
2
answers
83
views
Macro string Interpolation / How to unquote inside string?
I have a macro like:
(defmacro test [x] `"~x")
After running it expands to the following:
=> (test abc)
'~x'
Why doesn't it expand to 'abc'?
What is the correct method to unquote inside ...
2
votes
2
answers
185
views
How to serialize hylang s-expression into PostgreSQL json/json-b?
We are trying to use hylang as DSL for some financial business flow. We were trying to use business rules as JSON, but switched to DSL using hy language. Now we need to persist s-expression items into ...
-1
votes
1
answer
88
views
Function Type Annotations
I think Hy is fantastic! Plan on using it, possibly even hacking on it.
I've noticed type annotations are supported, but apparently only for variables, and at most, function arguments. It doesn't seem ...
0
votes
1
answer
75
views
Why are calls to `defmacro` evaluating to None?
I was writing the following pieces of code:
(require [hy.contrib.walk [let]])
(defn maybe? [command-text]
(let [splitted (.split command-text " ")]
(= (get splitted 0) "maybe&...
0
votes
1
answer
131
views
Dictionary merging in Hy
If I have two dictionaries, and want to merge them with preference to the latter regarding conflicting keys, I would do in Python:
In [1]: x = {'a': 1, 'b': 2}
In [2]: y = {'b': 3, 'c': 4}
In [3]: {*...
0
votes
1
answer
137
views
How to declare 'main' in a hy program
As per the official docs, I should be able to to use
def main [ &rest _ ]
I tried the example in a let block :
(import argparse)
(require [hy.contrib.walk [let]])
(def main [&rest _]
(...
2
votes
1
answer
158
views
What is the difference between if and cond?
Perhaps I am misunderstanding something.
In Hy, if* can take (after the if* symbol)
one predicate (evaluation returned if there are no further expressions)
zero or one consequent (evaluated and ...
0
votes
0
answers
108
views
Calysto Hy not starting properly
I have run an intro to Hy session for the Atlanta Functional Programming meetup.
One audience for this intro is Pythonistas that might want to use Hy to get acquainted with a Lispy syntax by porting ...
0
votes
1
answer
114
views
How to use the pandas apply method in hy
I'd like to create a new column in pandas using the .apply method where I can pass a custom function
df["newcol"] = df["oldcol"].apply(lambda x: x + 1)
or
df["newcol"] = ...
0
votes
1
answer
93
views
macro for pandas column setting in hy
I feel I'm writing functions needlessly for the following operation of setting several derived columns sequentially:
(defn add-cols[d]
(do
(setv (get d "col0") "0")
(...
0
votes
1
answer
77
views
configure automatic Hy REPL imports
I've been absolutely loving the Hy REPL. However it would speed up my workflow immensely if I could have a set of default imports at startup. Clojure has a way of configuring startup imports via ...
0
votes
1
answer
91
views
How to construct AST of Hy lang snippets
I have several Hy Lang code snippets that I use in my python project.
I was wondering if there is a relatively easy way for me to get an Abstract Syntax Tree of the Hy code with some python library or ...