【发布时间】:2015-12-07 00:34:51
【问题描述】:
在阅读Lisp in Your Language 之后,我一直在尝试使用 Python。一切正常,直到我到达variable assignment and scoping。
最后的电话把我难住了。似乎在 javascript 中,可以创建一个新的范围对象并将对象分配或绑定到该新范围,而不是使用“this”。在链接的示例中:
// use existing local scope or create a new one
scope = scope || {};
[...]
// call the function with these arguments
// and expose scope as this
return fn.apply(scope, args);
在 Python 中,这似乎是不可能的。在此之前我一直在调用return fn(*args),但现在我对如何编写等效代码感到困惑。
有什么想法或建议吗?
编辑:我已经找到了解决这个问题的方法,至少现在是这样:
# defined outside of the function
global scope_dict
scope_dict = {}
def pl_def(name, value):
global scope_dict
scope_dict[name] = value
return scope_dict[name]
[...]
# use existing scope inside the function
global scope_dict
scope = scope_dict
# resolve all our new string names from our scope
def symbol_check(symbol):
if isinstance(symbol, list):
return symbol
elif symbol in scope:
return scope[symbol]
else:
return symbol
expression = [symbol_check(x) for x in rawExpr]
[...]
# call the function with these arguments
return fn(*args)
【问题讨论】:
-
最简单的方法是运行函数,它们有自己的本地命名空间。如果您明确要创建范围,可以使用
exec()。
标签: python python-3.x scope