Python:有没有办法从包装它的装饰器中获取局部函数变量? [英] Python: Is there a way to get a local function variable from within a decorator that wraps it?

查看:382
本文介绍了Python:有没有办法从包装它的装饰器中获取局部函数变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从包装它的装饰器中读取对象方法的局部值。
我可以从装饰器中访问函数和func_code,但似乎只能从本地var的名称中获取,而不能从它们的值中获取。

I'd like to read an object method's local value from a decorator that wraps it. I've got access to the function and func_code from within the decorator but it seems all I can get out of it is the names of the local vars, but not their values.

有可能吗?

推荐答案

请参见https://stackoverflow.com/a/4249347/224295 http://code.activestate.com/recipes/577283-decorator-to-expose-local-variables-of-afunction-/

工作示例:

import sys

class persistent_locals(object):
    def __init__(self, func):
        self._locals = {}
        self.func = func

    def __call__(self, *args, **kwargs):
        def tracer(frame, event, arg):
            if event=='return':
                self._locals = frame.f_locals.copy()

        # tracer is activated on next call, return or exception
        sys.setprofile(tracer)
        try:
            # trace the function call
            res = self.func(*args, **kwargs)
        finally:
            # disable tracer and replace with old one
            sys.setprofile(None)
        return res

    def clear_locals(self):
        self._locals = {}

    @property
    def locals(self):
        return self._locals

@persistent_locals
def func():
    local1 = 1
    local2 = 2

func()
print func.locals

这篇关于Python:有没有办法从包装它的装饰器中获取局部函数变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆