hy

Is there a way to capture a name from the environment when using hy.eval?


I'm trying to create functions in hylang and use them from python but the created functions don't seem to have access to the environment passed to hy.eval.

import hy

env = dict(x=5)
func = hy.eval(hy.read_str('(fn [] x)'), env)
print(func())

The call to func results in NameError: name 'x' is not defined. I also tried

hy.eval(hy.read_str('(func)'), env)

without luck (same error). Any ideas?


Solution

  • hy.eval doesn't have a globals parameter but it has a module parameter and by looking at the source I found that module.__dict__ is passed as globals to eval. So the following works:

    import hy
    from types import ModuleType
    
    env = dict(x=5)
    module = ModuleType('<string>')
    module.__dict__.update(env)
    func = hy.eval(hy.read_str('(fn [] x)'), module=module)
    print(func())