开发者

Find all decorated functions in a module

Is it possible to find out if a function is decorated at runtime? For example could I find all functions in a module that are开发者_StackOverflow社区 decorated by "example"?

@example
def test1():
    print "test1"


Since you have indicated that you have the control over the wrapper code, here is an example:

def example(f):
    f.wrapped = True
    return f

@example
def test1():
    print "test1"

def test2():
    print "test2"


print test1.wrapped
print hasattr(test2, 'wrapped')


In the general case it is not possible because the example decorator might not leave any trace that's detectable at runtime -- for example, it could be

def example(f):
  return f

If you do control the source for example, it's of course easy to make it mark or record the functions it's decorating; if you don't, it may be utterly impossible to do what you want.


I don't think there's a general way since a decorator is a simple function call. Your code is identical to this:

def test1():
    print "test1"

test1 = example(test1)

You could probably detect specific decorators by disassembling and analysing (using the dis module). Or you could simply parse the source file, though that's a bit ugly.

Why do you want to detect them in the first place?


You may find this recent question provides detailed information on 3 ways to do this:

Howto get all methods of a python class with given decorator


If you can, monkeypatch the decorator at runtime to catch which functions are being passed to it:

decfuncs = []

def decpatch(dec):
  def catchdec(func, *args, **kwargs):
    decfuncs.append(func)
    return dec(func, *args, **kwargs)
  return catchdec

somemodule.somedecorator = decpatch(somemodule.somedecorator)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜