Saturday, December 06, 2014

Hy <-> Python Interop

I added Hy <-> Python Interop documentation to the Hy documentation today! Best part of open source is that if you find something missing, you can just add it!

Hy <-> Python interop

By importing Hy, you can use Hy directly from Python!
If you save the following in greetings.hy:
(defn greet [name] (print "hello from hy," name))
Then you can use it directly from python, by importing hy before importing the module. In Python:

import hy
import greetings


You can also declare a function in python (or even a class!) and use it in Hy!
If you save the following in in Python:

def greet(name):
    print("hello, %s" % (name))

You can use it in Hy:

(import greetings)
(.greet greetings "foo")

To use keyword arguments, you can use in

def greet(name, title="Sir"):
    print("Greetings, %s %s" % (title,name))

and then in Hy:

(import greetings)
(.greet greetings "Foo")
(.greet greetings "Foo" "Darth")
(apply (. greetings greet) ["Foo"] {"title" "Lord"})

Which would output:

Greetings, Sir Foo

Greetings, Darth Foo

Greetings, Lord Foo

Simple as that! Now keep on the Hy life!

No comments:

Post a Comment