在不访问 属性 值的情况下,内省 class 属性 以查看它是否被装饰

Introspect class property to see if it is decorated, without accessing property value

这是我正在处理的简化版本:

def mydecorator(prop):
    def wrapper(self_arg):
        return prop(self_arg) + 'bar'
    return wrapper

class Foo(object):

    def __init__(self):
        self.value = 'foo'

    @property
    @mydecorator
    def foo(self):
        return self.value

    @property
    def doesnt_have_my_decorator(self):
        return 'something that requires a lot of computation'

f = Foo()

print f.foo # prints 'foobar'

现在我想做的是自省 f.foo,而不实际访问它的值,并检查它是否用 @mydecorator 装饰。这可能吗?

用例是能够在特定上下文中将 属性 列入白名单 "safe",而无需实际访问它的值,以防它是 "unsafe"。

我看过 this great post,但似乎该方法要求 foo 已经被访问过。

我发现我可以看到它是一个 property with:

f.__class__.__dict__['foo'].__class__

但我没能找到任何对 mydecorator 的引用。既然是Python,我肯定有办法,但我至今没能弄清楚...

在 Python 中,装饰器只是一种缩短的语法。例如:

@property
@mydecorator
def foo(self):
    return self.value

与此完全相同:

def foo(self):
    return self.value

foo = property (mydecorator (foo))

由于您的装饰器不会在其 return 值上留下任何可检测的痕迹,因此无法确定它是否已被应用。您可以改写为例如:

def mydecorator(prop):
    def wrapper(self_arg):
        return prop(self_arg) + 'bar'
    wrapper._mydecorator = True
    return wrapper

然后用这个表达式来测试一下:

hasattr (type (f).foo.fget, '_mydecorator')