使用 hy.eval 时有没有办法从环境中捕获名称?

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

我正在尝试在 hylang 中创建函数并从 python 使用它们,但创建的函数似乎无法访问传递给 hy.eval 的环境。

import hy

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

func 的调用导致 NameError: name 'x' is not defined。我也试过了

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

没有运气(同样的错误)。有什么想法吗?

hy.eval的第一个参数是locals,而不是Python的evalglobals。不过,隐式使用调用环境效果很好,因此您可以更直接地将其写为

 import hy

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

hy.eval 没有 globals 参数,但它有一个 module 参数,通过查看源代码,我发现 module.__dict__ 作为 globalseval。所以以下工作:

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())