3

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?

Brant
  • 5,721
  • 4
  • 36
  • 39
  • 1
    Look this way: http://stackoverflow.com/questions/3232024/introspection-to-get-decorator-names-on-a-method – lecodesportif Apr 01 '11 at 15:37
  • The answer on that question is a bad idea. Don't make up your own special magic for applying decorators. – Glenn Maynard Apr 01 '11 at 16:19
  • Thanks for the link but it isn't quite what I was looking for. I was hoping there was just some python function or attribute that was used for detecting the decorator. – Brant Apr 01 '11 at 16:49
  • In general, almost certainly not. A decorator is just a callable which takes some function, and replaces it with a new one. If you know something about the decorators that might be applied, you can check for their effects. – Thomas K Apr 01 '11 at 17:12
  • That's about what I'm finding... – Brant Apr 01 '11 at 17:32

1 Answers1

3

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.

ojii
  • 4,729
  • 2
  • 23
  • 34
  • That's quite handy... that ends up returning to me with a set of "cells"... I'm having a hard time interfacing with those cells though. I can't seem to find examples of how to pull attributes/methods out of the cells... any advice? – Brant Apr 04 '11 at 15:30