在Python中检测装饰器 [英] Detect Decorator in Python
问题描述
在python中,是否可以检测到另一个函数上是否存在装饰器?
In python, is it possible to detect if there is a decorator on another function?
具体来说,我正在尝试(在django中)编写一些中间件将检测正在处理的视图是否已包装在@login_required装饰器中。
Specifically, I'm trying (in django) to write some middleware that will detect if the view being processed has been wrapped in the @login_required decorator.
class SomeMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if has_decorator(view_func):
print "this view was decorated"
我要填写的是 has_decorator部分...。
What I'm trying to fill in is the "has_decorator" portion....
这可能吗?
推荐答案
在外壳中快速浏览一下即可显示 func_closure
函数的属性在未修饰的函数中为空,但在修饰的函数中包含数据。并非总是100%地确定这是真的,但这也许对您有用。
Just some quick fooling around in the shell shows that the func_closure
attribute on a function is empty on undecorated functions, but contains data in decorated functions. Not 100% sure this is true all the time, but maybe this works out for you.
这篇关于在Python中检测装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!