Detect Decorator in Python

一个人想着一个人 提交于 2019-12-10 18:52:25

问题


In python, is it possible to detect if there is a decorator on another function?

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"

What I'm trying to fill in is the "has_decorator" portion....

Is this possible?


回答1:


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.



来源:https://stackoverflow.com/questions/5515520/detect-decorator-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!