【问题标题】:How to access a decorated method local variables ( locals() ) from inside a Python decorator?如何从 Python 装饰器中访问装饰方法局部变量( locals() )?
【发布时间】:2011-10-30 17:06:05
【问题描述】:

这是我需要的:

假设我有这个装饰器:

def deco(func):
    def decoret(*args, **kwargs):
        print(func.__locals__) # I know __locals__ is not valid, but I need something like this
    return decoret

@deco
def func():
    test1 = 123
    test2 = 456

func()

我想获取 所有局部变量 的列表(就像我在函数内部调用 locals() 一样),所以我可以使用 test1 和 test2 访问 字典装饰器的 decoret 函数中的值

我知道我可以通过使用 Python 检查模块来做到这一点,但我无法跟踪正确的帧来获取函数。

另外,我使用的是 Python 3.2 CPython。

【问题讨论】:

    标签: python python-3.x decorator


    【解决方案1】:

    在函数执行之前,没有局部变量。当它被装饰时,你唯一可用的东西就是它被定义时的东西。

    d = 'd'
    def a(d=d):
        b = 'b'
        c = 'c'
    
    print a.__dict__
    # {}
    print a.b
    # AttributeError: 'function' object has no attribute 'b'
    print dir(a)
    # Doesn't print anything
    

    【讨论】:

    • 你是对的,我错了,因为我用它来用 CherryPy 和 Tenjin 创造一些魔法(实际上是为了摆脱每次都需要将字典返回到模板。) ,我会找到另一个解决方案。
    【解决方案2】:

    实际上,我找到了一种方法来规避并使用来自 sys 的跟踪来实现这一点。

    看看这个sn-p:

    def Property(function):
        keys = 'fget', 'fset', 'fdel'
        func_locals = {'doc':function.__doc__}
        def probeFunc(frame, event, arg):
            if event == 'return':
                locals = frame.f_locals
                func_locals.update(dict((k,locals.get(k)) for k in keys))
                sys.settrace(None)
            return probeFunc
        sys.settrace(probeFunc)
        function()
        return property(**func_locals)
    

    从位于http://code.activestate.com/recipes/410698/ 的代码的 sn-p 中获取此信息

    另外,看看这个 stackoverflow 主题:Python: static variable decorator

    【讨论】:

    • 请...不要用大写命名函数
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多