vasili111
vasili111

Reputation: 6930

How to include Hy code inside python code?

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.

Upvotes: 1

Views: 331

Answers (2)

Kodiologist
Kodiologist

Reputation: 3495

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')")

Upvotes: 3

Tobias
Tobias

Reputation: 1371

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.

Upvotes: 2

Related Questions