Introspection to get decorator names on a method?

后端 未结 8 1576
滥情空心
滥情空心 2020-12-01 08:00

I am trying to figure out how to get the names of all decorators on a method. I can already get the method name and docstring, but cannot figure out how to get a list of dec

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 08:00

    That's because decorators are "syntactic sugar". Say you have the following decorator:

    def MyDecorator(func):
        def transformed(*args):
            print "Calling func " + func.__name__
            func()
        return transformed
    

    And you apply it to a function:

    @MyDecorator
    def thisFunction():
        print "Hello!"
    

    This is equivalent to:

    thisFunction = MyDecorator(thisFunction)
    

    You could embed a "history" into the function object, perhaps, if you're in control of the decorators. I bet there's some other clever way to do this (perhaps by overriding assignment), but I'm not that well-versed in Python unfortunately. :(

提交回复
热议问题