How to include Hy code inside python code?

Question:

For example we have this Hy code:

(print "Hy, world!")

And we have two pieces of Python code. Piece one:

print("Some python code")

Piece two:

print("Some other python code")

How can we make something like this:

print("Some python code")
(print "Hy, world!")
print("Some other python code")

Please also include appropriate imports. I have not found right way to import Hy.

Asked By: vasili111

||

Answers:

Per the manual:

import hy

print("Some python code")
hy.eval(hy.read('(print "Hy, world!")'))
print("Some other python code")

Note that the Hy code is compiled at run-time. We’ll probably never be able to implement embedding Hy code in a Python script so that it can be compiled at the same time the Python code is compiled. You can do the reverse and embed Python in Hy, though:

(pys "print('Some python code')")
(print "Hy, world!")
(pys "print('Some other python code')")
Answered By: Kodiologist

You put your hy code into a separate file and name it example.hy (or whatever):

(print "Hello World")

Inside your Python-script, you then simply import hy first, and afterwards you import example just as you would with a Python module.

import hy
import example

The reason this works is because hy installs an import hook when you do import hy, which allows it to find hy-files, compile them and then import them just like any other Python module.

Answered By: Tobias
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.