Search code examples
pythonpython-3.xevalhy

python3/hy - evaluating hy expressions in python?


I know how to import an hy module into python. All I have to do is create a something.hy file containing hy code and then do the following ...

import hy
import something
something.func('args') # assumes there is an hy function called `func`

However, I haven't been able to figure out how to evaluate a string within python which contains hy code. For example ...

hycode = '(print "it works!")'
hy.SOMEHOW_EVALUATE(hycode)
# I'd like this to cause the string `it works!` to print out.

Or this example ...

hycode = '(+ 39 3)'
result = hy.SOMEHOW_EVALUATE(hycode)
# I'd like result to now contain `42`

When using hy within python, is there any way to evaluate strings in this manner?


Solution

  • Use hy.read_str and hy.eval.

    >>> import hy
    >>> hy.read_str("(+ 39 3)")
    HyExpression([
      HySymbol('+'),
      HyInteger(39),
      HyInteger(3)])
    >>> hy.eval(_)
    42
    >>> hycode = hy.read_str('(print "it works!")')
    >>> hycode
    HyExpression([
      HySymbol('print'),
      HyString('it works!')])
    >>> hy.eval(hycode)
    it works!
    

    This works if you install Hy from Github master. If you need to make it work on an old version of Hy, you can see the implementation in the hy package's __init__.py is simply

    from hy.core.language import read, read_str  # NOQA
    from hy.importer import hy_eval as eval  # NOQA