Using Hy, a dialect of Lisp for Python, with QGIS
So tonight I rediscovered Hy. I had seen Hy before a while ago but never really sat down and tried it. Tonight just must have been one of those days to try something new.
So Hy is a dialect of Lisp but embedded in Python which means you can use any Python library will using a Lisp dialect. Pretty nifty.
My next thought was, how would this look using the QGIS libraries. So lets give it a try.
First we need to install Hy:
pip install Hy
Now just create a .hy file and add some code
(import qgis) (import [qgis.core [QgsVectorLayer]]) (import [qgis.core.contextmanagers [qgisapp]]) (setv layers []) (defn load-layer [file name] (setv layer (QgsVectorLayer file name "ogr")) (.append layers layer)) (defn print-layer [layer] (print "Layer Name:" (.name layer)) (print "Valid:" (.isValid layer)) (print "Extents:" (.toString (.extent layer)))) (defn main [app] (load-layer r"F:gis_datatest.shp" "test") (for [layer layers] (print-layer layer))) (with [[app (apply qgisapp [] {"guienabled" False})]] (print "Loading QGIS") (main app))
run it in our shell and bingo.
F:devhy-qgis>hy qgistest.hy Loading QGIS Layer Name: test Valid: True Extents: 392515.3457026787800714,6461581.2076761415228248 : 392683.3794420150225051,6461705.1012571481987834
Sweet.
Just for reference the Python version of the above would be:
import qgis from qgis.core import QgsVectorLayer from qgis.core.contextmanagers import qgisapp layers = [] def load_layer(file, name): layer = QgsVectorLayer(file, name, "ogr") layers.append(layer) def print_layer(layer): print "Layer Name:", layer.name() print "Valid:", layer.isValid() print "Extents:", layer.extent().toString() def main(app): load_layer(r"F:gis_datatest.shp", "test") for layer in layers: print_layer(layer) with qgisappl(guienabled=False) as app: main(app)
More readable? No doubt, that is why I love Python, however the strange thing is the first time I looked at Lisp, including Hy, I thought “whoa all those parentheses back it up!1!” but strangely after using it for a while (read: not even a few hours) they don’t seem to be an issue, or not much of one anyway. YMMV.
The cool thing with using Hy is you can still use all the libraries you are used to as the example above shows, PyQt, QGIS, anything.
The other interesting, and pretty funky, thing is that you are able to import .hy files like normal Python files. If you create a file winning.hy
you can just import winning
into any Python application and it works.
Why bother? Mainly because learning something new is never a bad thing, and you never know what you might pick up.
Check out the Hy for more info on what you can do and how it works
I have also created a hy-qgis GitHub repo for some experiments.
Enjoy!
Filed under: Open Source