Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a list of the decorators applied to a function?

Is there any way I can obtain a list of the decorators applied to a function without resorting to hackish things like decorating the decorators?

like image 602
alexgolec Avatar asked Sep 16 '25 09:09

alexgolec


1 Answers

Not really. First, because not all decorators return a wrapper function; it is possible for a decorator to simply modify the existing function (setting an attribute on it, perhaps) -- Python doesn't record what function touched every attribute, obviously. Second, while you can probably ask the garbage collector for closures that hold a reference to the decorated function, and to functions that have that closure, not every function that holds a reference to another function in a closure is a wrapper applied by a decorator. Then there's the issue of decorators that take arguments; there is an extra layer of inner functions before you get to the actual decorating function. Finally, not all decorators are functions, and not all decorated objects are functions.

In short, you might be able to approximate it some of the time, but even when it works, it's going to be an enormous hack that only works on CPython. There just isn't any simple, documented way to do it.

like image 161
kindall Avatar answered Sep 19 '25 03:09

kindall