1

I wonder if there is a way to enumerate decorators of the function while I have its reference during runtime.

Let’s say I have a list of functions in the runtime and I wish to know if they were decorated.

@app.route('/foo/bar', methods=['POST'], schema=Payload)
def some_endpoint(self, request, payload):
    return f'Some response'

Or for an example, I wish to know if an instance of function I have in runtime has a concrete decorator like @deprecated.

Example:

@deprecated
def foo():
    # Implementation

It would be really interesting to find an access for a decorator especially if it is a decorator class.

Python version 3.6.2

kuza
  • 2,761
  • 3
  • 22
  • 56
  • 3
    In general, no. Applying a decorator is just syntactic sugar for applying function to a value. `@deprecated def foo(): ...` is *exactly* the same as `def foo(): ...; foo = deprecated(foo)`. – chepner Aug 16 '17 at 12:21
  • What @chepner said. Your original function might not even exist anymore, because it's replaced by the return value of the decorator - unless the decorator explicitly keeps an accessible reference to the original function (as decribed in this answer [here](https://stackoverflow.com/a/1166200/4349415)). – Mike Scotty Aug 16 '17 at 12:22
  • @chepner To be absolutely precise (or pedantic), it's not *exactly* the same: the decorator syntax generate two bytecode instructions less than the `f = dec(f)` syntax (disassembled in Python 3.6). For what it's worth... – Right leg Aug 16 '17 at 12:39
  • The decorator names can be obtained by introspection via the ast module (see [this answer](https://stackoverflow.com/a/31197273/984421)). – ekhumoro Aug 16 '17 at 12:42
  • @ekhumoro thanks you helped me find answers as I failed due to miss formulation of the question but a suggested answer that you mentioned failing in Python 3.6.2. It seems like accepted answer is the only workaround. – kuza Aug 16 '17 at 13:15

0 Answers0