如何在Python中创建动态范围变量?

时间:2010-01-04 18:09:53

标签: python variables lisp scope dynamic-scope

我正在将一些代码从lisp转换为Python。

在lisp中,你可以有一个let构造,引入的变量声明为特殊的,因此具有动态范围。 (见http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping

我怎样才能在Python中做同样的事情?看来语言不直接支持这个,如果是真的,那么什么是模仿它的好方法呢?

4 个答案:

答案 0 :(得分:11)

我认为正义在他的推理中是正确的。

另一方面 - 我无法抗拒为Python的另一个编程范例“不自然”实现概念验证 - 我只是喜欢这样做。 : - )

所以,我创建了一个类,其对象的属性就像你需要的那样被scopped(并且可以动态创建)。正如我所说,它只是在概念证明状态 - 但我认为最常见的错误(如试图访问范围内的变量,它根本没有定义)应该会引发错误,即使不是正确的错误(IndexError)由于堆栈下溢而不是AttributeError,例如)

import inspect


class DynamicVars(object):
    def __init__(self):
        object.__setattr__(self, "variables", {})

    def normalize(self, stackframe):
        return [hash(tpl[0]) for tpl in stackframe[1:]]

    def __setattr__(self, attr, value):
        stack = self.normalize(inspect.stack())
        d = {"value": value, "stack": stack}
        if not attr in self.variables:
            self.variables[attr] = []
            self.variables[attr].append(d)
        else:
            our_value = self.variables[attr]
            if our_value[-1]["stack"] == stack:
                our_value[-1]["value"] = value
            elif len(stack) <= len(our_value):
                while our_value and stack !=  our_value["stack"]:
                    our_value.pop()
                our_value.append(d)
            else: #len(stack) > len(our_value):
                our_value.append(d)
    def __getattr__(self, attr):
        if not attr in self.variables:
            raise AttributeError
        stack = self.normalize(inspect.stack())
        while self.variables[attr]:
            our_stack = self.variables[attr][-1]["stack"]
            if our_stack == stack[-len(our_stack):]:
                break
            self.variables[attr].pop()
        else:
            raise AttributeError
        return self.variables[attr][-1]["value"]


# for testing:
def c():
    D = DynamicVars()
    D.c = "old"
    print D.c
    def a():
        print D.c
    a()
    def b():
        D.c = "new"
        a()
    b()
    a()
    def c():
        D.c = "newest"
        a()
        b()
        a()
    c()
    a()

c()

答案 1 :(得分:11)

这里的东西有点像Lisp的特殊变量,但在Python中更合适。

_stack = []

class _EnvBlock(object):
    def __init__(self, kwargs):
        self.kwargs = kwargs
    def __enter__(self):
        _stack.append(self.kwargs)
    def __exit__(self, t, v, tb):
        _stack.pop()

class _Env(object):
    def __getattr__(self, name):
        for scope in reversed(_stack):
            if name in scope:
                return scope[name]
        raise AttributeError("no such variable in environment")
    def let(self, **kwargs):
        return _EnvBlock(kwargs)
    def __setattr__(self, name, value):
        raise AttributeError("env variables can only be set using `with env.let()`")

env = _Env()

你可以像这样使用它:

with env.let(bufsize=8192, encoding="ascii"):
    print env.bufsize  # prints 8192
    a()  # call a function that uses env.bufsize or env.encoding

env.let阻止with阻止持续时间的效果。

请注意,如果您使用线程,那么您肯定希望每个线程都有不同的_stack。您可以使用threading.local来实现它。

答案 2 :(得分:6)

与Lisp“特殊”或动态范围变量对应的Python习语是“线程本地存储”。

以下是一个很好的讨论:What is "thread local storage" in Python, and why do I need it?

如果要完全模拟Lisp的特殊变量,包括let语句,可以使用上下文管理器:

from __future__ import with_statement # if Python 2.5
from contextlib import contextmanager
import threading

dyn = threading.local()

@contextmanager
def dyn_vars(**new):
    old = {}
    for name, value in new.items():
        old[name] = getattr(dyn, name, None)
        setattr(dyn, name, value)
    yield
    for name, value in old.items():
        setattr(dyn, name, value)

示例(显然是愚蠢的,但它显示了可重入的特征):

def greet_self():
    print 'Hi', dyn.who_am_I

def greet_selves():
    with dyn_vars(who_am_I='Evil Twin'):
        greet_self()
    greet_self()

with dyn_vars(who_am_I='Tobia'):
    greet_selves()

答案 3 :(得分:-6)

动态范围被认为是有害的。

不要使用它;不要效仿它。

如果需要模拟它,请定义dynamic_scope模块以模拟此行为并在所有源文件中导入模块。此模块应具有方法begin,这些方法在函数的第一行中使用动态范围endgetset进行调用。 getset方法应实现查找调用链的调用链,其中调用链由beginend实现。然后重构代码以消除动态范围。

相关问题