描述当前作用域的对象



我使用的API定义了这样一个方法:

def show_prop(object, propname): #...

它应该做的是通过调用getattr(object, propname)在屏幕上显示属性,并允许用户更改属性,从而产生setattr(object, propname)

我没有办法改变这种行为,但我想使用API向用户显示一个局部变量,并从用户接收正常的反馈?

我想到了一个描述当前范围和可用变量的构建变量,有点像本地的__dict__,但我还没有找到这样的东西。

userinput = "Default input"
show_prop(__mysterious_unknown__, 'userinput')
# Do something exciting with the changed userinput

这可能实现吗?

No。本地写访问只能直接在作用域中完成,或者使用nonlocal在嵌套作用域中完成(仅限Python3)。

Python没有"指针"的概念,指定可写位置的唯一方法是传递对容器的引用和成员的"名称"(或数组的索引,字典的键)。

你能做的就是动态地创建一个小对象:

class Bunch:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
def foo():
    my_local = 42
    ...
    myobj = Bunch(my_local=my_local) # create the dummy instance
    show_prop(myobj, "my_local")     # call the original code
    my_local = myobj.my_local        # get modified value back
    ...

在Python3中可以创建一个神奇的对象实例,当写入成员时将动态地改变局部(使用新的Python3 nonlocal关键字和属性或__getattr__/__setattr__捕获全部)。我不喜欢这种奇怪的魔法,除非真的需要……

例如:

def foo(obj, name):
    # the fixed API
    setattr(obj, name, 1 + getattr(obj, name))
def bar():
    myloc = 11
    # magic class...
    class MyClass:
        def __getattr__(self, name):
            # accessing any member returns the current value of the local
            return myloc
        def __setattr__(self, name, value):
            # writing any member will mutate the local (requires Python3)
            nonlocal myloc
            myloc = value
    foo(MyClass(), "myloc")
    print(myloc) # here myloc will have been incremented
bar()

最新更新